Check Strings在php中有匹配的关键字

时间:2017-08-22 06:54:14

标签: php regex

我有两个输入或字符串将传递给PHP函数。

例1:

$string1 = "good tutorial for learning";
$string2 = "good tutorial are available in website";

例2:

$string1 = "learning is a good habit";
$string2 = "good habit to refer website";

我需要检查两个字符串是否具有相同的关键字(例如:良好的教程,良好的习惯)或不是

if($string1 contains matching keyword with $string2 ){
     echo true;
}

任何帮助将不胜感激。提前谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个

<?php
$string1 = "these is a good tutorial for the learning";
$string2 = "good tutorial are available in website";

$string1 = explode(' ',$string1);
$string2 = explode(' ',$string2);

$match = '';

foreach($string1 as $keyword){
       if(in_array($keyword,$string2)){
                  $match.=' '.$keyword;
        }
 }
 echo $match;
?>

答案 1 :(得分:0)

<?php
$input = "good tutorial";
$string1 = "these is a good tutorial for the learning";
$string2 = "good tutorial are available in website";

if(preg_match("/".$input."/", $string1) && preg_match("/".$input."/", $string2))
    echo 'true';

这样的东西?

答案 2 :(得分:0)

如果您尝试从两个字符串中查找常用单词,可以尝试以下方法:

<?php
$string1 = "these is a good tutorial for the learning";
$string2 = "good tutorial are available in website";

$words1  = explode(' ', $string1);
$words2  = explode(' ', $string2);

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

var_dump($strings_in_common);

输出:

array (size=2)
  3 => string 'good' (length=4)
  4 => string 'tutorial' (length=8)

如果您正在搜索字符串并检查它们是否包含某些子字符串/单词:

<?php
function contains_all_words_in_strings(array $words, array $strings) {
    foreach($strings as $string) {
        if (array_diff($words, explode(' ', $string)))
            return false;
    }

    return true;
}


$string1 = "these is a good tutorial for the learning";
$string2 = "good tutorial are available in website";

$words = array('good', 'tutorial');
var_dump(contains_all_words_in_strings($words, array($string1, $string2)));

$words = array('good', 'foo');
var_dump(contains_all_words_in_strings($words, array($string1, $string2)));

输出:

boolean true
boolean false

(当然这些字符串都有简单的标点符号。它们很可能需要一些预处理/规范化。)