PHP Match String Pattern and Get Variable
I've searched for some links like this question and this question , but couldn't figure out what I need to do.
I am trying to do the following:
Let's say I have two lines:
$str1 = "link/usa";
$str2 = "link/{country}";
Now I want to check if the pattern matches the pattern. If they match, I want the country value to be set to usa.
$country = "usa";
I also want it to work in cases like:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
Maybe whole numbers. Like combining all curly braces and assigning a value to the variable. (And, yes, it's better if possible)
I can't seem to work as I am very new to regex. Thank you in advance.
source to share
This will give you the results as expected
$str1 = "link/usa";
$str2 = "link/{country}";
if(preg_match('~link/([a-z]+)~i', $str1, $matches1) && preg_match('~link/{([a-z]+)}~i', $str2, $matches2)){
$$matches2[1] = $matches1[1];
echo $country;
}
Note. The above code will just parse alphabets, you can expand the characters in the range as needed.
UPDATE:
You can also do it with explode
, see example below:
$val1 = explode('/', $str1);
$val2 = explode('/', $str2);
${rtrim(ltrim($val2[1],'{'), '}')} = $val1[1];
echo $country;
UPDATE 2
$str1 = "link/usa/texas/2/";
$str2 = "/link/{country}/{city}/{page}";
if(preg_match_all('~/([a-z0-9]+)~i', $str1, $matches1) && preg_match_all('~{([a-z]+)}~i', $str2, $matches2)){
foreach($matches2[1] as $key => $matches){
$$matches = $matches1[1][$key];
}
echo $country;
echo '<br>';
echo $city;
echo '<br>';
echo $page;
}
source to share
I don't see any point in using a key as a variable name if you can build an associative array that is probably more convenient to use later and avoids ugly dynamic variable names ${the_name_of_the_var_${of_my_var_${of_your_var}}}
:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
function combine($pattern, $values) {
$keys = array_map(function ($i) { return trim($i, '{}'); },
explode('/', $pattern));
$values = explode('/', $values);
if (array_shift($keys) == array_shift($values) && count($keys) &&
count($keys) == count($values))
return array_combine($keys, $values);
else throw new Exception ("invalid format");
}
print_r(combine($str2, $str1));
source to share