2013-03-21 118 views
0

今晚实现了我使用的剥离功能之一似乎是随机跳过单词。Wordstrip函数跳过没有明显原因的单词。

<?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; 
    } 

?>

它跳过单词 “the”,我不知道为什么。该名单是类似200字长,我知道它的工作,因为它删除大多数其他字词。

我喂它“最后一封信给乔治W布什和迪克切尼从垂死的老兵” 并得到回“最后一封信乔治W布什和迪克切尼从一个垂死的老将”

我认为它是由于“/ \”,因为“the”是在字符串的开始。我试过“/ \?但那没有奏效。我想我只需要让空间可选就可以了?

谢谢

+0

http://codepad.org/rhBk6PmH – 2013-03-21 00:36:09

回答

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; 
+0

你为什么要'strtolower()'而不是'/ i'? – 2013-03-21 00:40:06

+0

@JaredFarrish - 这不是我的代码...只是使用问题。 – Daedalus 2013-03-21 00:40:28

+0

啊 - 没有注意到原来的。考虑针对TheEditor。 – 2013-03-21 00:41:02

相关问题