我有以下正常的正则表达式。
$str = "ID: {{item:id}} & First name: {{item:first_name}} & Page Title: {{page:title}}";
preg_match_all('/(?<={{)[^}]*(?=}})/', $str, $matches);
print_r($matches);
Returns:
Array
(
[0] => Array
(
[0] => item:id
[1] => item:first_name
[2] => page:title
)
)
如何修改正则表达式以强制它匹配项目:id和item:仅限first_name(或以&#34开头的任何其他字符串; item:&#34;)?我尝试添加&#34;项目&#34;到正则表达式(在几个不同的地方),但它没有工作。
答案 0 :(得分:1)
您可以使用:
preg_match_all('/(?<={{)item:[^}]*(?=}})/', $str, $matches);
print_r($matches[0]);
Array
(
[0] => item:id
[1] => item:first_name
)
答案 1 :(得分:0)
使用此功能,您可以对令牌进行分组,因此您无需将表达式限制为任何单一类型:
(?<={{)(.+?)(?:\:)(.+?)(?=}})
利用示例:
$str = "ID: {{item:id}} & First name: {{item:first_name}} & Page Title: {{page:title}}";
preg_match_all('/(?<={{)(.+?)(?:\:)(.+?)(?=}})/', $str, $matches);
$tokens = array();
foreach ($matches[0] as $i => $v) {
$tokens[$matches[1][$i]][] = $matches[2][$i];
}
echo '<pre>';
print_r($tokens);
输出:
Array
(
[item] => Array
(
[0] => id
[1] => first_name
)
[page] => Array
(
[0] => title
)
)