Php Wordstrip函数无明显原因跳过单词。
今晚意识到我正在使用的剥离函数之一似乎是随机跳过单词Php Wordstrip函数无明显原因跳过单词。,php,regex,sanitization,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 = strto
<?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·布什和迪克·切尼的最后一封信”
我认为这是由于“/\s”造成的,因为“the”在字符串的开头。我尝试了“/\s?”,但不起作用。我想我只需要将空格设置为可选的,对吗
谢谢你你可以用\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;
为什么你要strtolower()
而不是/i
?@JaredFarrish-这不是我的代码。。。只是用了被问到的东西。啊-在原文中没有注意到。考虑一下编辑吧。谢谢我的正则表达式很糟糕,我从来没有使用过/b,但效果很好。@JaredFarrish我只是从来没有真正想过它。当我得到一份真正有效的声明时,我很高兴,但/我会是一个更聪明的解决方案。谢谢你。