PHP在字符串中直接删除单词

时间:2014-10-30 06:06:07

标签: php preg-replace strpos preg-split

我正在编写一个搜索引擎。基本上,如果出现某个单词,我需要在该单词之后立即抓住并删除该单词。

如果说瑜伽'发生了,我需要在它之后删除这个词,这里是垫子。所以我会得到:

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

我看过strpos,但需要一个字。我也有preg_split它按名称删除单词,但我还需要按位置删除这个特定的单词。

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

如果瑜伽之后的单词并不总是垫子,我该如何删除瑜伽后的单词。我仍然需要很多话。

3 个答案:

答案 0 :(得分:6)

此代码段应该可以满足您的需求:

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

代码非常不言自明:用句子分隔句子,识别所有具有“瑜伽”值的键,取消设置下一个单词,并从剩余的单词中重构句子。

答案 1 :(得分:1)

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

echo preg_replace('#(\b' . preg_quote($word) . '\b)\W*\b\w+\b#U', '$1', $sentence);

但下一个"字"可以是''''等等。为了跳过那些不是"单词"应该创建列表并添加其他操作。

ps:好的,regexp的解释

#  - start of regexp
(  - start of capture  
 \b - boundary of the word
 preg_quote($word)  - escaped word to find
 \b - boundary of the word
) - close capture group
\W* - any non-word characters
\b - boundary of the next word
\w+ - word characters
\b - boundary
# - end of regexp
U - un-greedy modifier

匹配的内容被捕获组$1

的内容替换

答案 2 :(得分:0)

<?php

    $user_input = "tea";
    $sentence="I like tea mats a lot.";
    $word_to_remove = $user_input . " ";
    $offset = strlen( $word_to_remove );

    $start_pos = stripos( $sentence , $word_to_remove );
    $end_pos = stripos( $sentence , " ", $start_pos+$offset );
    $str_to_replace = trim( substr( $sentence , $start_pos+$offset, ($end_pos-$offset)-$start_pos ) );

    $new_sentence = str_replace( $str_to_replace, "", $sentence );
    $new_sentence = preg_replace( "/\s+/", " ", $new_sentence);

    echo $new_sentence;

?>