tags:

views:

188

answers:

3

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

A: 

Depends, str_replace might be what you're looking for. But note that it removes all occurrences.

asnyder
+2  A: 

Try this:

$fixed_string = str_replace(" WORD ", "  ", $your_string);
Andrew Hare
Surely you meant to replace it with a single space? Additionally, this won't match words at the beginning, end, or before punctuation (e.g. "this, word" or "this: word", etc.)
James Burgess
The OP asked for the most efficient way to remove "WORD" from the sentence they offered. My solution is the most efficient way but you are right that it may not be the best solution given the fact that the OP undoubtedly has other requirements that aren't in the question.
Andrew Hare
I see your point about the double-space replacement (i.e. only removing the word itself).
James Burgess
+5  A: 

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.

yjerem