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...
?
CodePudding user response:
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
CodePudding user response:
Here's a long-winded solution, but user3783243 is the better answer.
$str = 'here is some text <img src="" alt="|||namrepus"> also some more text <img src="" alt="|||namtab">';
$i = strpos($str, "|||", $i);
while ($i != false) {
$j = strpos($str, '"', $i);
$c = substr($str, $i, $j-$i);
$r = substr(strrev($c), 0, strlen($c)-3);
$str = substr_replace($str, $r, $i, $j-$i);
$i = strpos($str, "|||", $i strlen($c));
}
echo htmlspecialchars($str);
exit();