Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I find all instances of a string starting with a certain character and replace the rest of the string using preg_replace / preg_match

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...?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading