Search code examples
phparraysstringcharactersimilarity

Looking for the same chars in two strings in PHP


Given two strings, what is the best approach in PHP to retrieve the characters which are in common, and those which are not?

For instance, given the two strings:

postcard

car

I would like to get something like:

letters in common: c - a - r
letters not in common: p - o - s - t - d

I saw there are word similarity functions which return a numeric value.

However, I would like to retrieve each single char.

My approach would be to treat both strings as arrays (using str_split) and then check if the elements in the shortest string are present in the longer one (using in_array).

$arr_postcard = str_split($postcard);
$arr_car = str_split($car);
$notcommon = array();
   if (in_array($arr_postcard, $arr_car) == false){
       array_push($notcommon, $arr_car);
   }
   foreach($notcommon as $k => $v){
      print_r ($v);
   }

The code above doesn't seem to work. It returns the values of $arr_car.

Maybe there are other ways.


Solution

  • A simple way to do so:

    <?php
    
    $postcard = 'paccoi';
    $car = 'coi';
    
    $arr_postcard = str_split($postcard);
    $arr_car = str_split($car);
    
    
    function array_diff_once($array1, $array2) {
        foreach($array2 as $a) {
            $pos = array_search($a, $array1);
            if($pos !== false) {
                unset($array1[$pos]);
            }
        }
    
        return $array1;
    }
    
    $uncommon = count($arr_postcard) >= count($arr_car) ?  array_diff_once($arr_postcard,$arr_car) : array_diff_once($arr_car,$arr_postcard);
    
    echo 'Letters not in common: ' . implode(' - ', $uncommon) . PHP_EOL;
    
    function array_intersect_once($array1, $array2) {
        $array = [];
        foreach($array1 as $a) {
            $pos = array_search($a, $array2);
            if($pos !== false) {
                $array[] = $a;
            }
        }
    
        return $array;
    }
    $common = count($arr_postcard) >= count($arr_car) ?  array_intersect_once($arr_car,$arr_postcard) : array_intersect_once($arr_postcard,$arr_car);
    
    echo 'Letters in common: ' . implode(' - ', $common) . PHP_EOL;
    

    Output: https://3v4l.org/lY755 and https://3v4l.org/kK9sE

    Note:- you can use trim() inside str_split() to overcome the problem of string with leading or trailing spaces.

    Reference taken: Keep Duplicates while Using array_diff