Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: delete word from sentence

Tags:

php

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

like image 641
Simon Avatar asked Apr 16 '10 22:04

Simon


People also ask

How do I remove a specific word from a string in PHP?

The default PHP function str_replace(); is a useful tool if we want to remove certain characters, symbols or words from a string.

How to find and replace word in string in PHP?

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.

Which script can you use in a regular expression in PHP to remove the last word from a string?

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.


2 Answers

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.

like image 55
Paige Ruten Avatar answered Sep 28 '22 06:09

Paige Ruten


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

like image 23
asnyder Avatar answered Sep 28 '22 05:09

asnyder