我查找了一些类似这道题和这道题的参考资料,但不知道我该怎么做。
我想做的是:
比如说,我有两个字符串:
$str1 = "link/usa";
$str2 = "link/{country}";
现在我想检查这个模式是否匹配。如果匹配,我希望country的值设置为usa。
$country = "usa";
我也希望它能在以下情况下工作:
$str1 = "link/usa/texas";
$str2 = "link/{country}/{place}";
也可能是整数。比如匹配每个大括号并为变量提供值。(是的,如果可能的话,性能会更好)
我不能得到一个工作,因为我是非常新的正则表达式。提前感谢。
它会给你预期的结果
$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;
}
注意:以上代码只解析字母,你可以根据需要扩展字符范围
更新:
你也可以使用explode
,见下面的例子:
$val1 = explode('/', $str1);
$val2 = explode('/', $str2);
${rtrim(ltrim($val2[1],'{'), '}')} = $val1[1];
echo $country;
更新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;
}
我不认为使用键作为变量名的意义,因为你可以建立一个关联数组,这可能会更方便以后使用,并避免编写丑陋的动态变量名${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));