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