Finding common characters in strings

最后都变了- 提交于 2019-12-12 03:19:32

问题


I am tring this method to find the common characters in two strings namely, $a and $r, but the first character isn't getting printed . Moreover the $already collects the common characters and prevents them from being printed for multiple times( I need each character to be printed once only) but it isn't doing so. Please tell me what errors I am making.

<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$already="";
for($i=0;$i<strlen($r);$i++)
{
   if (stripos($a,$r[$i])!=FALSE)
   {
        if (stripos($already,$r[$i])==FALSE)
        {
            $already=$already.$r[$i];
            echo "already=".$already."<br>";
            echo $r[$i]."<br>";
        }
   }
}
?>

回答1:


Use !==FALSE instead of !=FALSE. The problem is that stripos returns 0 if the needle is at the start of the haystack, and 0 is falsy. By using !== you are forcing it to ensure the result is actually false, and not just 0.

This is actually listed in the docs. An "RTM" might be appropriate here.

Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.




回答2:


The simplest way to find the intersection of the two strings in PHP is to turn them into arrays and use the built-in functions for that purpose.

The following will show all the unique and common characters between the two strings.

<?php
    $a="BNJUBCI CBDIDIBO";
    $r="SBKJOJLBOU";

    $a_arr = str_split($a);
    $r_arr = str_split($r);

    $common = implode(array_unique(array_intersect($a_arr, $r_arr)));

    echo "'$common'";
?>



回答3:


I would think a much simpler solution to this would be to make the strings into arrays and compare those no?

Something like:

<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";

$shared = implode( '' , array_intersect( str_split($a) , str_split($r) ) );
?>

That should return you a string of all the characters in $a that are present in $r



来源:https://stackoverflow.com/questions/9878570/finding-common-characters-in-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!