Replace Certain Words in Paragraph

I need to write a PHP function that will search a body of text (e.g. article, user comment, etc.) and replace certain works with alternatives.

For example, for all occurrences of “internet” it would replace them with “Internet”.

Or for all occurrences of “Excel” it would replace them with “Microsoft Excel”.

I would use http://php.net/manual/en/function.str-replace.php

You can have an array of words to replace and their replacements

This seems to be more complicated than I had hoped.

What is the difference between str_replace and say preg_replace??

Also, how can I avoid the The Clbuttic Mistake??

I’m not sure if this is more of a PHP or a Regex question…

I would guess you can have more control with preg_replace but it would be more complicated.

The problem is if you replace “dog” with “cat” and you have a doghouse in a sentence it would become a cathouse. This is where preg_replace may come into its own as you could instruct it to only change the word if it had for instance a white space before or after the selected word.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.