繁体   English   中英

用正则表达式替换和提取匹配项

[英]Replace and extract matches with regex

如何使用例如preg_match_all()获得所有匹配项,并将结果替换为空字符串?

我已经尝试过这样的事情:

<?php
$comments   = array();              

$selectors  = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) {
    $comments[] = $match[0];
    return '';
}, $input);
?>

但这并不是很好,因为$ comment变量似乎无法从匿名函数访问。 我想我可以创建全局变量,但是我真的不想弄乱这样的名称空间

这应该工作:

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM