Im trying to extract a specific value from multiple strings. Lets say i have the following strings:
/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}
I want to extract all between curly bracket open and _hash}, how can i achieve this?
The output should be a array:
$array = [
'some_hash',
'user_hash',
'date_hash',
'user_hash'
];
Current code:
$matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/({.*?_hash})/', $url, $matches);
}
You can use regex for that:
$s = '/a-url/{some_hash}/
/user/{user_hash}/
/user-overview/{date_hash}/{user_hash}';
preg_match_all('/{(.*?_hash)}/', $s, $m);
var_dump($m[1]);
The output will be:
array(4) {
[0]=>
string(9) "some_hash"
[1]=>
string(9) "user_hash"
[2]=>
string(9) "date_hash"
[3]=>
string(9) "user_hash"
}
Based on your edit you probably want:
$all_matches = [];
foreach (\Route::getRoutes()->getRoutes() as $route) {
$url = $route->getUri();
preg_match_all('/{(.*?_hash)}/', $url, $matches);
$all_matches = array_merge($all_matches, $matches[1]);
}
var_dump($all_matches);
Related
I’m trying to extract three parts with a regular expression.
It works for the controller and the id but not for the slug, I can not remove the last -
<?php
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z]+)\/(?<slug>[a-z0-9\-]+)(?<=\-)(?<id>[0-9]+)/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value){
if(!is_numeric($key)){
$routes[$key] = $value;
}
}
var_dump($routes);
I get the following result :
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(20) "my-second-article-2-"
["id"]=>
string(3) "155"
}
But i want this slug :
["slug"]=>
string(20) "my-second-article-2"
Thanks
You may use the following regex pattern:
/(?<controller>[a-z]+)\/(?<slug>[a-z0-9]+(?:-[a-z0-9]+)+)-(?<id>[0-9]+)/i
Your updated PHP script:
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z]+)\/(?<slug>[a-z0-9]+(?:-[a-z0-9]+)+)-(?<id>[0-9]+)/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value) {
if (!is_numeric($key)) {
$routes[$key] = $value;
}
}
var_dump($routes);
This prints:
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(19) "my-second-article-2"
["id"]=>
string(3) "155"
}
The final portion of the updated regex says to match:
[a-z0-9]+ alphanumeric term
(?:-[a-z0-9]+)+ followed by hyphen and another alphanumeric term, both 1 or more times
- match a literal hyphen
[0-9]+ match the id
i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>
Using PHP 8.0.
I want to search a line for regex matches and replace all those matches with a string. Here is the code I wrote to find matches:
// $lines is an array of html document lines
function include_files(array $lines): array {
$pattern = '/{FILE="[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+"}/';
foreach ($lines as $line){
preg_match_all($pattern, $line, $matches);
var_dump($matches);
foreach ($matches[0] as $match) {
$file_name = get_block_file($match[0]);
$file_content = file_get_contents($file_name);
$line = str_replace($match[0], $file_content, $line);
}
}
return $lines;
}
The problem is that var_dump($matches) displays the following:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(1) { [0]=> string(6) "{FILE="1.txt"" } }
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
One of these arrays contains what I need, but neither can I accesses it nor can I understand where do all these other arrays come from. How can I fix this behavior?
preg_replace and preg_replace_callback can take an array as the subject, so you don't need the loop or multiple replaces. You didn't supply any sample data for $lines so assuming your pattern works as needed:
$pattern = '/{FILE="[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+"}/';
$lines = preg_replace_callback($pattern,
function($m) {
return file_get_contents(get_block_file($m[0]));
}, $lines);
I think that your problem is related with $matches variable, because this variable is inserted by reference &$matches and "n" iterations are being inserted.
preg_match_all ( string $pattern , string $subject , array &$matches = null , int $flags = 0 , int $offset = 0 ) : int|false|null
A possible solution would be to initialise the variable to null before calling the function preg_match_all
Example:
$pattern = '/{FILE="[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+"}/';
foreach ($lines as $line){
$matches = null;
preg_match_all($pattern, $line, $matches);
I have not been able to test it, but I think it can be a quick solution.
This is my string: $string="VARHELLO=helloVARWELCOME=123qwa";
I want to get 'hello' and '123qwa' from string.
My pseudo code is.
if /^VARHELLO/ exist
get hello(or whatever comes after VARHELLO and before VARWELCOME)
if /^VARWELCOME/ exist
get 123qwa(or whatever comes after VARWELCOME)
Note: values from 'VARHELLO' and 'VARWELCOME' are dynamic, so 'VARHELLO' could be 'H3Ll0' or VARWELCOME could be 'W3l60m3'.
Example:
$string="VARHELLO=H3Ll0VARWELCOME=W3l60m3";
Here is some code that will parse this string out for you into a more usable array.
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$parsed = [];
$parts = explode('VAR', $string);
foreach($parts AS $part){
if(strlen($part)){
$subParts = explode('=', $part);
$parsed[$subParts[0]] = $subParts[1];
}
}
var_dump($parsed);
Output:
array(2) {
["HELLO"]=>
string(5) "hello"
["WELCOME"]=>
string(6) "123qwa"
}
Or, an alternative using parse_str (http://php.net/manual/en/function.parse-str.php)
<?php
$string="VARHELLO=helloVARWELCOME=123qwa";
$string = str_replace('VAR', '&', $string);
var_dump($string);
parse_str($string);
var_dump($HELLO);
var_dump($WELCOME);
Output:
string(27) "&HELLO=hello&WELCOME=123qwa"
string(5) "hello"
string(6) "123qwa"
Jessica's answer is perfect, but if you want to get it using preg_match
$string="VARHELLO=helloVARWELCOME=123qwa";
preg_match('/VARHELLO=(.*?)VARWELCOME=(.*)/is', $string, $m);
var_dump($m);
your results will be $m[1] and $m[2]
array(3) {
[0]=>
string(31) "VARHELLO=helloVARWELCOME=123qwa"
[1]=>
string(5) "hello"
[2]=>
string(6) "123qwa"
}
I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"