Search code examples
phpregexreplacepreg-replaceplaceholder

Replace placeholder between two pipes with an HTML <img> tag and use the placeholder's value as the src value


I can't get this regex to replace pipe-wrapped placeholders with <img> tags:

$string = 'blah blah |one|';
$search = array('/|one|/','/|two|/');
$string = preg_replace($search,"'<img src=\"\"'.str_replace('|','','\\0').'\".png\"/>'",$string);

I need it to return blah blah <img src="one.png"/> in this case, but having trouble dealing with the function inside the replacement.


Solution

  • Is there any reason for this "function call" (which is just a string)? How about capture groups? And you have to escape the |, because they are special characters (alternation):

    $string = 'blah blah |one|';
    $search = array('/\\|(one)\\|/','/\\|(two)\\|/');
    $string = preg_replace($search,'<img src="$1.png"/>',$string);
    

    DEMO