Search code examples
phpreplacepreg-replacestr-replacepreg-replace-callback

preg_replace reverse/mutual replacing on synonyms words


I want to mutual or reverse replace on synonyms words. I have to give an example to tell you:

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
$find = array('/ipsum/', '/amet/');
$replace = array('amet', 'ipsum');
$output = preg_replace($find, $replace, $string);

Output is:

Lorem ipsum dolor sit ipsum, consectetur adipiscing elit

Expected output is should be like that:

Lorem amet dolor sit ipsum, consectetur adipiscing elit

So i want to change all ipsum to amet and amet to lorem. These two words that "ipsum" and "amet" just samples. I have thousands synonyms words.

Like you see, i tried preg_replace function but doest work.


Solution

  • use strtr:

    $string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
    $find = array('ipsum', 'amet');
    $replace = array('amet', 'ipsum');
    $trans = array_combine($find, $replace);
    
    $result = strtr($string, $trans);
    

    The main difference with str_replace is that string is parsed only once, when str_replace (or preg_replace) parses it once for each item.

    Not very interesting for you example but you can do it to with preg_replace_callback:

    $trans = ['ipsum' => 'amet', 'amet'=>'ipsum'];
    $result = preg_replace_callback('~amet|ipsum~', function ($m) use ($trans) {
        return $trans[$m[0]]; }, $string);
    

    If you want to achieve the same with str_replace or preg_replace you need to use a placeholder:

    $find = ['ipsum', 'amet', '###placeholder###'];
    $replace = ['###placeholder###', 'ipsum', 'amet'];
    $result = str_replace($find, $replace, $string);