I've been working on a little project, and I've come to a sudden halt. I have been helping a friend on their website, and they want to replace every second use of a set word. For example... So, if they had the string : "I like Keyword . For the Keyword is a useful part of the string. Without the Keyword there would be no need for this post. So how can I replace every alternate Keyword within the string?" How would I go about making it : "I like Keyword . For the Replacement is a useful part of the string. Without the Keyword there would be no need for this post. So how can I replace every alternate Replacement within the string?" I have googled for regex examples and examples using preg_replace , however, all I can find is how to replace every example of the keyword. All help is greatly appreciated
<?php $str = "I like Keyword . For the Keyword is a useful part of the string. Without the Keyword there would be no need for this post. So how can I replace every alternate Keyword within the string?"; $keyword = 'Keyword'; $replacement = 'Replacement'; $str = preg_replace('#(\b' . preg_quote($keyword) . '\b.+?)\b' . preg_quote($keyword) . '\b#is', "$1{$replacement}", $str); echo $str; ?> PHP:
Thank you for the response. I'm still getting used to regex and preg_replace etc. Is there any chance that you could explain how your regex is replacing every second match of keyword? and is this easily adaptable for say every 3rd or 5th match instead of second? Again, your help is much appreciated
Have a look at the following to learn more about regex: http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html (a great intro) http://www.php.net/manual/en/regexp.reference.delimiters.php (what are delimiters?) http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php (what are modifiers?) http://php.net/manual/en/function.preg-quote.php Experiment with the following code changing $match to whatever match you'd like to replace. <?php $str = "I like Keyword . For the Keyword is a useful part of the string. Without the Keyword there would be no need for this post. So how can I replace every alternate Keyword within the string?"; $keyword = 'Keyword'; $replacement = 'Replacement'; //the third match? - change this to whatever... $match = 3; $str = preg_replace('#('.str_repeat('\b' . preg_quote($keyword) . '\b.+?', $match - 1).')\b' . preg_quote($keyword) . '\b#is', "$1{$replacement}", $str); echo $str; ?> PHP: