PHP preg_replace() backreferences used as arguments of another function

I am trying to extract information from a tags using a regex, then return a result based on various parts of the tag.

preg_replace('/<(example )?(example2)+ />/', analyze(array($0, $1, $2)), $src);

So I’m grabbing parts and passing it to the analyze() function. Once there, I want to do work based on the parts themselves:

function analyze($matches) {
    if ($matches[0] == '<example example2 />')
          return 'something_awesome';
    else if ($matches[1] == 'example')
          return 'ftw';
}

etc. But once I get to the analyze function, $matches[0] just equals the string ‘$0‘. Instead, I need $matches[0] to refer to the backreference from the preg_replace() call. How can I do this?

Thanks.

EDIT: I just saw the preg_replace_callback() function. Perhaps this is what I am looking for…

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can’t use preg_replace like that. You probably want preg_replace_callback

Solution 2

$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);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply