Search code examples
phppreg-replacestrpospreg-split

PHP remove the word directly after another in string


I am coding a search engine.Basically, if a certain word occurs I need the word immediately after that word to be grabbed and removed.

If the word 'yoga' occurs, I need to remove the word right after it, here 'mats'.So I would get:

$sentence="I like yoga mats a lot.";
$word="mats";
$result=I like yoga a lot.

Ive looked at strpos, but need it for a word. I also have preg_split it to remove words by name, but I additionally need to remove this specific word by position.

$separate = preg_split('/\s+/', $sentence);

How would I remove the word after 'yoga', given that the word after it is not always mats. And I still need the words a lot to be there.


Solution

  • This code snippet should do what you are looking for:

    $words = explode(' ', $sentence);
    foreach (array_keys($words, 'yoga') as $key) {
      unset($words[$key+1]);
    }
    $sentence = implode(' ', $words);
    

    The code is pretty self-explanatory: separate the sentence in words, identify all keys that have the value 'yoga', unset the next word, and recompose the sentence from the remaining words.