Wordstrip函数跳过单词没有明显的原因。

时间:2013-03-21 00:30:00

标签: php regex sanitization

今晚意识到我正在使用的一个剥离功能似乎是随机跳过单词。

<?php
function wordstrip($document){ 
  //I truncated the list here for brevity
$wordlist = array(
"it39s",
"039",
"the",
"while",
"message");

//convert all uppercase to lower so matches work correctly
$document = strtolower($document);
            foreach($wordlist as $word)

            $document = preg_replace("/\s". $word ."\s/", " ", $document);
            //echo $word;
            //echo $document;
            $nopunc = preg_replace('/[^a-z0-9]+/i', ' ', $document);
            $trimmed = trim($nopunc);
            return $trimmed; 
    } 

&GT;

它正在跳过“the”这个词,我不知道为什么。这个列表长度大约200字,我知道它的工作,因为它删除了大多数其他的单词..

我喂它“最后一封信给乔治·W·布什和迪克·切尼来自垂死的退伍军人” 并找回了“乔治·布什和迪克·切尼从一位垂死的退伍军人那里的最后一封信”

我认为它归于“/ \ s”,因为“the”是在字符串的开头。我试过“/ \ s?”但那没用。我想我只需要让空格可选吗?

谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用\b来表示单词边界,而不是摆弄空格或句点或其他可能围绕单词的其他内容:

$document = strtolower($document);

foreach($wordlist as $word)
    $document = preg_replace("/\b". $word ."\b/", " ", $document);

$nopunc = preg_replace('/[^a-z0-9]+/i', ' ', $document);
$trimmed = trim($nopunc);
return $trimmed;
相关问题