i have the sentence
something about something
WORD still something...
what is the most efficient metod to delete the word "WORD" from sentence in php? thanks
The default PHP function str_replace(); is a useful tool if we want to remove certain characters, symbols or words from a string.
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
Explode the str with explode(delimiter, string) into an array $words , take the first word put it into $res , and iterate over words the count of $words times minus one which is exclude the last word.
You could replace it with nothing:
$sentence = str_replace('word', '', $sentence);
Although that would also ruin words like swordfish
, turning them into sfish
. So you could put spaces around the edges:
$sentence = str_replace(' word ', ' ', $sentence);
But then it won't match words at the end and beginning of sentences. So you might have to use a regex:
$sentence = preg_replace('/\bword\b/', '', $sentence);
The \b
is a word boundary, which could be a space or a beginning of a string or anything like that.
Depends, str_replace might be what you're looking for. But note that it removes all occurrences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With