[英]Replace and extract matches with regex
How can I get all matches with for example preg_match_all() and also replace the results with an empty string? 如何使用例如preg_match_all()获得所有匹配项,并将结果替换为空字符串?
I've tried stuff like this: 我已经尝试过这样的事情:
<?php
$comments = array();
$selectors = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) {
$comments[] = $match[0];
return '';
}, $input);
?>
But that doesn't work very well since the $comment variable doesn't seem to be accessable from the anonymous function. 但这并不是很好,因为$ comment变量似乎无法从匿名函数访问。 I guess I can make global variables, but I really don't want to mess up the namespace like that
我想我可以创建全局变量,但是我真的不想弄乱这样的名称空间
This should work: 这应该工作:
<?php
$comments = array();
$selectors = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) use (&$comments) { //add the variable $comments to the function scope
$comments[] = $match[0];
return '';
}, $input);
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.