PHP:如何比较2字符串中存在的任何一个单词

时间:2012-08-23 04:36:23

标签: php strpos

我的情况是这样的:

<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";

$var1 = strtolower($var1);
$var2 = strtolower($var2);

if (strpos($var1, $var2) !== FALSE) {
echo "TRUE";
}
?>

它无法正常工作,我如何检测TOP或英文两种字符串都存在?

4 个答案:

答案 0 :(得分:2)

从字符串中删除标点符号,将它们都转换为小写,将空格字符上的每个字符串分解为字符串数组,然后遍历每个字符串以查找匹配的单词:

$var1 = preg_replace('/[.,]/', '', "Top of British");
$var2 = preg_replace('/[.,]/', '', "Welcome to British, the TOP country in the world");


$words1 = explode(" ",strtolower($var1));
$words2 = explode(" ",strtolower($var2));

foreach ($words1 as $word1) {
    foreach ($words2 as $word2) {
       if ($word1 == $word2) {
          echo $word1."\n";
          break;
       }
    }
}

DEMO:http://codepad.org/YtDlcQRA

答案 1 :(得分:0)

在字符串中找到TOP或BRITISH

<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";

$var1 = strtolower($var1);
$var2 = strtolower($var2);

if (strpos($var1, 'top') && strpos($var1, 'british')) {
echo "Either the word TOP or the word BRITISH was found in string 1";
}
?>

更一般地将字符串2中的单词与字符串1中的单词匹配

<?php
$var1 = explode(' ', strtolower("Top of British"));
$var2 = "Welcome to British, the TOP country in the world";

$var2 = strtolower($var2);

foreach($var1 as $needle) if (strpos($var2, $needle)) echo "At least one word in str1 was found in str 2";

?>

答案 2 :(得分:0)

检查短语中单词交集的通用示例 您可以在结果中查看任何过时的停用词,例如“of”或“to”

<?php
$var1 = "Top of British";
$var2 = "Welcome to British, the TOP country in the world";

$words1 = explode(' ', strtolower($var1));
$words2 = explode(' ', strtolower($var2));

$iWords = array_intersect($words1, $words2);

if(in_array('british', $iWords ) && in_array('top', $iWords))
  echo "true";

答案 3 :(得分:0)

PHP具有查找属于两个数组的元素的函数:

$var1 = explode(" ", strtolower("Top of British"));
$var2 = explode(" ", strtolower("Welcome to British, the TOP country in the world"));
var_dump(array_intersect($var1, $var2)); // array(1) { [0]=> string(3) "top" }