代码之家  ›  专栏  ›  技术社区  ›  Meiji

如何逐字符比较两个字符串?

  •  -2
  • Meiji  · 技术社区  · 8 年前

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

    例如:

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

    上面的“o”存在于两个字符串中,因此算法应该 exist .

    2 回复  |  直到 8 年前
        1
  •  6
  •   Andreas    8 年前

    如果拆分字符串并删除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。

        2
  •  1
  •   AymDev    8 年前

    你可以用 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 将是一个包含字母的数组 l &安培; o :

    Array
    (
        [2] => l
        [3] => l
        [4] => o
    )
    
    推荐文章