Conditional use of str_replace

I am going through the articles on my website because I want to replace all instances of & in order to replace it with the word “and”. Here is the code I have for that:

$body = str_replace("&", "and", "$body");

But what is the best way to preserve a product name, “Peace & Calming”? That is the one exception I need to make to my code so that the name is not modified. Should I use an IF statement or preg_match?

Thank you!


The most simplest way to do that:

/* convert & to and */
$body = str_replace('&', 'and', $body);
/* convert it back for certain phrase */
$body = str_replace('Peace and Calming', 'Peace & Calming', $body); 

But obviously, that will work only for specified phrase.
If you want to make it more universal, you have to use regular expressions with preg_match().
It could be a very tricky task because it’s hard to define strict rules which words are product name and which are not.

Thank you Megazioid!

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