2

$end = preg_replace($pattern, $replacement, $str);

How can I make the replacement string $replacement vary with each match in $str? For example, I want to replace each matched string with an associated image. Something about callbacks... right?

2 Answers 2

3

Yes, something with callbacks. Specifically preg_replace_callback, which makes repeated calls redundant. For a list of things to replace:

 $src = preg_replace_callback('/(thing1|thing2|thing3)/', 'cb_vars', $src);

Where the callback can do some form of lookup or conversion:

 function cb_vars($m) {
     return strtoupper($m[1]);
 }

Likewise can you do that inline with the normal preg_replace and the /e modifier.

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

1 Comment

Yes! Awesome, I was having trouble reading the php docs. Thanks for spelling it out...
3

You need to either use preg_replace_callback, or the /e modifier in the pattern string. The first is more powerful, but the second is more convenient if you are only after something relatively simple.

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.