1

我的情况是这样的:

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

4

4 回答 4

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

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

于 2012-08-23T04:41:24.617 回答
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";

?>
于 2012-08-23T04:42:46.407 回答
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";
于 2012-08-23T04:44:05.467 回答
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" }
于 2012-08-23T04:45:00.030 回答