简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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