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


PHP: how to compare either of the word exist in 2 string

我的情况如下:

<?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或British?

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

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

演示:http://codepad.org/YtDlcQRA

在字符串中查找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";
?>

检查短语中单词交集的通用示例。。。您可以在结果中检查任何过时的停止词,如"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";

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" }