php正则表达式和或(|)

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 replace apple if it's the full word, then, as some others recommended, use word boundaries:

$text = preg_replace('#\b' . $oldWord . '\b#', $newWord, $text);

If you did intent to remove the spaces, too you could require a wordboundary, but make the spaces optional:

$text = preg_replace('#[ ]?\b' . $oldWord . '\b[ ]?#', $newWord, $text);

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.

Why not just str_replace('apple', 'orange', $text);?

EDIT:

Per comment from user:

preg_replace('/\bapple\b/', 'orange', $text);

If you're concerned about properly escaping the search word in the expression:

$oldWord = preg_quote($oldWord, '/');
$text = preg_replace("/\b$oldWord\b/", $newWord, $text);

simply use preg_replace instead of preg_match

preg_replace('⁓\b'.$oldWord.'\b⁓', $newWord, $text)

I can't test but

$text = preg_match('#\b' . $oldWord . '\b#ig', $newWord, $text);

Shoudl save your day ;)

So, if you want to replace the whole word only, that is, leave "pineapple" alone, then the str_replace method won't work. What you should be using is the word boundary anchor \b

preg_replace('#\b' + $oldWord + '\b#', $newWord, $text)