I have the following PHP code that makes HTML code for images from a predefined list:
$message = "thing.png, other.jpg, other.jpg, other.jpg, last.tiff, thing.png";
$keywords = array("thing.png", "other.jpg");
foreach ($keywords as &$value) $value = "/(".$value.")/";
echo $message = preg_replace($keywords, '<img src="images/$1" />', $message, 2);
I added a 2
to limit preg_replace
to make a maximum of two replacements.
This would generate following output:
<img src="images/thing.png">, <img src="images/other.jpg">, <img src="images/other.jpg">, other.jpg, last.tiff, <img src="images/thing.png">
I would like this instead:
<img src="images/thing.png">, <img src="images/other.jpg">, other.jpg, other.jpg, last.tiff, thing.png
Note that my desired behaviour limits preg_replace
to two replacements total, not two replacements per array (or needle).
Could you help me limit the code to two total replacements? Is this what preg_replace_callback
is for?
My final code:
$message = "thing.png, other.jpg, other.jpg, other.jpg, last.tiff, thing.png";
$keywords = array("thing.png", "other.jpg");
$regexp = "/".implode("|", array_map("preg_quote", $keywords))."/";
echo $message = preg_replace($regexp, '<img src="images/$0" />', $message, 2);