简体   繁体   English

检查并比较 PHP 中的两个字符串

[英]Check and compare two strings in PHP

I want to check two strings.我想检查两个字符串。 I want to use the method to check similarity or matching between two strings.我想使用该方法来检查两个字符串之间的相似性或匹配性。

Example:例子:

$str1 = "Samsung Galaxy Note 5";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

I want the result is match, because both strings have keyword "Samsung Galaxy Note 5".我希望结果是匹配的,因为两个字符串都有关键字“Samsung Galaxy Note 5”。

The other example:另一个例子:

$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

The result is not match, because both string don't have same keyword.结果不匹配,因为两个字符串没有相同的关键字。

What method can I use?我可以使用什么方法?

You can try this -你可以试试这个——

$str1 = "Samsung Galaxy Note 4";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

if(strpos(str_replace(' ', '', $str2), str_replace(' ', '', $str1)) !== 0) {
   echo "Not Matched!";
}

For the examples you have provided it should work.对于您提供的示例,它应该可以工作。

Since you are matching NOTE 5 and NOTE5 so you need to replace space and with the use of strpos由于您正在匹配 NOTE 5 和 NOTE5,因此您需要替换空间并使用strpos

$str1 = "Samsung Galaxy Note 5";
$str1 = str_replace(" ", "", $str1);
$str2 = "Samsung Galaxy Note 5 Black Smartphone";
$str2 = str_replace(" ", "", $str2);

if (strpos($str2,$str1) !== false) {
    echo 'true';
}else{
echo "not found";
}

You can use preg_match along with preg_replace like as您可以将preg_matchpreg_replace一起使用,如

$str1 = "Samsung Galaxy Note 5";
$str2 = "Samsung Galaxy Note5 Black Smartphone";

if(preg_match("/(".preg_replace('/[\h]/','',$str1).")/i",preg_replace('/[\h]/','',$str2))!==false){
    echo "match";
}

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM