4

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

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.