[英]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.