PHP - 从文本列表中提取单词

时间:2012-06-19 16:50:28

标签: php

我有一个白名单词列表:kitchen chair table;

鉴于文本,我想知道其中包含哪些列入白名单的单词。

实现这一目标的方法是什么?我的意思是,易于理解,表现良好?

5 个答案:

答案 0 :(得分:2)

不是一个非常明确的问题,但这样的事情对你有用:

$str = "kitchen chair table";
$search = "kitchen bathroom chair";
$arr1 = explode(' ', $str);
$arr2 = explode(' ', $search);
print_r(array_intersect($arr1, $arr2));

<强>输出:

Array
(
    [0] => kitchen
    [1] => chair
)

答案 1 :(得分:2)

要实现这一点,您应该使用带有字边界的正则表达式。如果你不这样做,只是依赖于字符串位置,那么“热”这样的词就会像“作弊”这样的单词匹配

$word_list = "kitchen chair table tables";
$words = explode( ' ', $word_list);

$text = 'There is a table in the kitchen';

foreach( $words as $word) {
    if( preg_match( '/\b' . $word . '\b/', $text)) {
        echo "$word is in the text\n";
    }
}

输出:

kitchen is in the text 
table is in the text 

请注意,如果table中只包含$text,则与tables不匹配。

答案 2 :(得分:1)

//list of words
$myArray = array('kitchen', 'chair', 'table');

foreach($myArray as $word){
    if(stristr($textBody, $word) !== false){
    // word's in there
    }
}

答案 3 :(得分:1)

您可以使用php explode函数使用空格分解wordlist。然后它会返回一个数组。输入文本也会做同样的事情。这样,你将有两个数组。

之后你可以使用array_intersect函数,它将返回两个数组中的常用字。

$array = explode(' ',$wordlist);
$result = array_intersect($array, $inputarray);

$ result将包含所有常用词。

答案 4 :(得分:1)

您是否需要知道这些单词在字符串中的频率或准确位置? 如果没有,我建议你将列表转换为“explode('',$ list)”数组。 然后迭代遍历该数组并使用strpos进行搜索。

如果您需要,我可以提供示例代码:)

如果您需要这些职位和所有事件,则必须使用正则表达式。

相关问题