PHP preg_replace()反向引用用作另一个函数的参数
-
05-07-2019 - |
题
我正在尝试使用正则表达式从标签中提取信息,然后根据标签的各个部分返回结果。
preg_replace('/<(example )?(example2)+ />/', analyze(array($0, $1, $2)), $src);
所以我抓住零件并将其传递给analyze()
函数。在那里,我想根据部件本身做工作:
function analyze($matches) {
if ($matches[0] == '<example example2 />')
return 'something_awesome';
else if ($matches[1] == 'example')
return 'ftw';
}
等。但是一旦我进入analyze函数,$matches[0]
就等于字符串'$0
'。相反,我需要<=>来引用preg_replace()调用的反向引用。我怎么能这样做?
感谢。
编辑:我刚看到preg_replace_callback()函数。也许这就是我要找的......
解决方案
您不能像这样使用preg_replace
。你可能想要 preg_replace_callback
其他提示
$regex = '/<(example )?(example2)+ \/>/';
preg_match($regex, $subject, $matches);
// now you have the matches in $matches and you can process them as you want
// here you can replace all matches with modifications you made
preg_replace($regex, $matches, $subject);
不隶属于 StackOverflow