Reputation: 507
$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?
Upvotes: 2
Views: 942
Reputation: 145482
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.
Upvotes: 3
Reputation: 437376
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.
Upvotes: 3