I’m trying to do a (reverse) replace of a certain string found within another string as follows:
$str = 'here is some text <img src="" alt="|||namrepus"> also some more text <img src="" alt="|||namtab">';
I’m looking for a way to get the following as a result:
$str = 'here is some text <img src="" alt="superman" also some more text <img src="" alt="batman">';
Does this require a loop to perform preg_match until it can no longer find instances of |||nam...?
>Solution :
You can use preg_replace_callback for this with strrev in the callback function.
echo preg_replace_callback('/[|]{3}(\w+)/', function($match){
return strrev($match[1]);
}, 'here is some text <img src="" alt="|||namrepus"> also some more text <img src="" alt="|||namtab">');
[|] searches for a |
{3} searches for 3 of the previous character/group
() creates a capture group, everything matched inside is inside a group
\w is a word character (a-zA-Z0-9_)
+ is one or more of previous char/group