如何比较一个字符一个字符地比较两个字符串?

时间:2018-08-07 10:16:33

标签: php string-comparison

假设我们有两个字符串,我想逐个字符地比较它们,以检查字符串a和字符串b中的任何字符是否匹配?

一个例子:

$a = "Hello";  
$b = "world";  

以上两个字符串中都存在'o',因此算法应回显exist

2 个答案:

答案 0 :(得分:5)

如果拆分字符串并使用array_unique删除重复项,则array_intersect将为您提供两个字符串中的字符。

$a = "Hello";
$b = "world";

$matching = array_unique(array_intersect(str_split(strtolower($a)), str_split(strtolower($b))));
if(count($matching)>0) echo "matching characters: " . implode(", ", $matching); 
//matching characters: l, o

按照罗恩的建议添加了strtolower。

答案 1 :(得分:1)

您可以使用str_split()转换字符串,并使用array_intersect()获得匹配的字符:

$a = "Hello";
$b = "world";

$matching_chars = array_intersect(
    str_split($a),
    str_split($b)
);

if (empty($matching_chars)) {
    echo 'exist';
}

$matching_chars将是一个包含字母lo的数组:

Array
(
    [2] => l
    [3] => l
    [4] => o
)
相关问题