I am experimenting a problem with | (or) and the regex in php.
Here is what I would like to do, for example I have those 3 sentences :
“apple is good to eat”
“an apple a day keeps the doctor away”
“i like to eat apple”
And lets say that i would like to change the word apple by orange, so here is my code :
$oldWord="apple";
$newWord="orange";
$text = preg_replace('#^' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . ' #', $newWord, $text);
$text = preg_replace('# ' . $oldWord . '$#', $newWord, $text);
Of course it works but i haven’t found the right combinaison to do that with only one line of code with the key word | (or).
Do you guys have any suggestion please ? thanks
Note that your regex removes the spaces around
apple. If this is not what you desire, but instead you just want to replaceappleif it’s the full word, then, as some others recommended, use word boundaries:If you did intent to remove the spaces, too you could require a wordboundary, but make the spaces optional:
If they are there, they will be removed, too. If they are not, the regex doesn’t care. Note that
[ ]is completely equivalent to just typing a space, but I find it more readable in a regex.