具有前瞻性和后视性的正则表达式

Regex with lookahead and lookbehind

我有以下正则表达式,效果很好。

$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
        )
)

我需要如何修改正则表达式以强制它仅匹配 item:id 和 item:first_name(或任何其他以 "item:" 开头的字符串)?我尝试将 "item" 添加到正则表达式(在几个不同的地方),但它没有用。

您可以使用:

preg_match_all('/(?<={{)item:[^}]*(?=}})/', $str, $matches);

print_r($matches[0]);
Array
(
    [0] => item:id
    [1] => item:first_name
)

有了它,您可以对标记进行分组,因此您无需将表达式限制为任何单一类型:

(?<={{)(.+?)(?:\:)(.+?)(?=}})

使用示例:

$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
        )

)