RSD
RSD

Reputation: 55

Compare two strings and remove or replace same characters in php

I want to compare two strings (variable1 and variable2) and i want to remove the matching characters from both strings(Only once).

For example: Variable1 : Apple, Variable2 : Ball

I tried using

array_diff(str_split('ball'), str_split('apple')) 

but i got only

b (it removed all matching characters.)

Expected Output is

  • bl (letters A,L(only once) removed from the second strings.)
  • ppe (letters A,L(only once) removed from the first strings.)

How to remove the characters only once ?

Upvotes: 1

Views: 920

Answers (2)

Gajanan Kolpuke
Gajanan Kolpuke

Reputation: 155

You can handle this through for-each

$a = 'ball';
$b = 'apple';

$arr1 = str_split($a);
$arr2 = str_split($b);

$firstArr = ( count($arr1) > count($arr2) ) ? $arr2 : $arr1;
$secondArr = ( count($arr1) < count($arr2) ) ? $arr2 : $arr1;

$objSecondArray = [];
$res = [];
foreach ($secondArr as $value) {
    $objSecondArray[$value] = 1;
}

foreach( $firstArr as $val ){
  if(array_key_exists($val, $objSecondArray) && $objSecondArray[$val] == 1) {
    $objSecondArray[$val] = null;
    continue;
  }
  $res[] = $val;
}

print_r($res);

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You need to do workaround for this using foreach() like below:-

$array1 = str_split(strtolower($variable1));
$array2 = str_split(strtolower($variable2));

if(count($array1) >= count($array2)){
    foreach($array1 as $key=>$arr){
        foreach($array2 as $k=>$arr2){
            if($arr == $arr2){
               unset($array1[$key]);
               unset($array2[$k]);
               break;
            }
        }

    }

}

if(count($array2) >= count($array1)){
    foreach($array2 as $key=>$arr){
        foreach($array1 as $k=>$arr1){
            if($arr == $arr1){
               unset($array2[$key]);
               unset($array1[$k]);
               break;
            }
        }

    }
}
print_r($array1);
print_r($array2);

Output:- https://3v4l.org/dp0ui

Upvotes: 2

Related Questions