views:

353

answers:

2

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

A: 
$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);
RaYell
+6  A: 

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

Alan Storm