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.
question from:https://stackoverflow.com/questions/65641097/looking-for-the-same-chars-in-two-strings-in-php