Str Replace multiple words at once

Discussion in 'PHP' started by mani_mani, Oct 1, 2012.

  1. #1
    I'm trying to work on script that can automatically change synonyms in an article to a single phrase so that I can spin the article but the script is outputting the results incorrectly. I was helped on this code from another website.

    <?php
    
    $a = array( 'story', 'tale', 'storyline', 'adventure' );
    $str = 'The story of the book is really nice. The tale starts with a boy. The storyline progresses...';
    echo str_replace($a,'{story|tale|storyline}',str_replace('Lexus','Toyota',$str));
    
    ?> 
    PHP:
    The script outputs:
    The {story|{story|tale|{story|tale|storyline}}|{story|tale|storyline}} of the book is really nice. The {story|tale|{story|tale|storyline}} starts with a boy. The {story|{story|tale|{story|tale|storyline}}|{story|tale|storyline}}line progresses...


    Instead it should be:
    The {story|tale|storyline} of the book is really nice. The {story|tale|storyline} starts with a boy. The {story|tale|storyline} progresses...
     
    mani_mani, Oct 1, 2012 IP
  2. amcd

    amcd Active Member

    Messages:
    7
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    88
    #2
    Nothing unusual here. Your replacement string contains some words which are also in your search array.

    If you really want to keep it this way, make it a two step process. First, search the array and replace it with a placeholder like 'found_string_176' or something. Then replace all instances of the placeholder with the final string.
     
    amcd, Aug 13, 2013 IP
  3. samyak

    samyak Active Member

    Messages:
    280
    Likes Received:
    7
    Best Answers:
    4
    Trophy Points:
    90
    #3
    I am guessing that you want to replace all occurance of story, tale or storyline to {story|tale|storyline}. But like amcd said, the replacement string contains the search string, so its being replace multiple times. To achieve this, use the function I created below instead of the str_replace.
    
    function samyak_replace($array, $text, $str)
    {
        $regex = "/".implode("|", $array)."/";
        return  preg_replace($regex, "{story|tale|storyline}", $str);
       
    }
    
    PHP:
    Use it like this:
    
    $a = array( 'story', 'tale', 'storyline', 'adventure' );
    $str = 'The story of the book is really nice. The tale starts with a boy. The storyline progresses...';
    echo  samyak_replace($a,'{story|tale|storyline}',str_replace('Lexus','Toyota',$str));
    
    PHP:
     
    samyak, Aug 13, 2013 IP