PHP如何比较两个变量之间的字符串并只显示唯一的字符串?

问题描述 投票:-3回答:2

注意:这里是S.O.有很多方法可以使用数组键,在相同变量的值/单词之间,两个不同的数组之间进行此操作,但我在互联网上看不到字符串之间的任何内容,而不是两个不同变量的数组。

<?php
$a = 'this car is very beautiful and is the fast';
$b = 'this red car is very beautiful and is the fast that others';
var_export($unique_words = show_unique_strings($a, $b));
//expected output(painted on the screen): red that others
?>
php string-comparison
2个回答
5
投票

正如Siphalor所说,这是一个实现

$a = 'this car is very beautiful and is the fast';
$b = 'this red car is very beautiful and is the fast that others';
echo $unique_words = show_unique_strings($a, $b);
//expected output(painted on the screen): red that others

function show_unique_strings($a, $b) {
  $aArray = explode(" ",$a);
  $bArray = explode(" ",$b);
  $intersect = array_intersect($aArray, $bArray);
  return implode(" ", array_merge(array_diff($aArray, $intersect), array_diff($bArray, $intersect)));
}

1
投票
<?php
$a = 'this car is very beautiful and is the fast';
$b = 'this red car is very beautiful and is the fast that others';

var_dump(getUniqWords($a, $b));

function getUniqWords($str1, $str2){
    $aWords = explode(" ", $str1);
    $bWords = explode(" ", $str2);
    $results[] = array();

    if(count($aWords) > count($bWords)){
        for($i=0;$i<count($aWords);$i++){
            if(!in_array($aWords[$i], $bWords)){
                array_push($results, $aWords[$i]);
            }
        }
    }else{
        for($i=0;$i<count($bWords);$i++){
            if(!in_array($bWords[$i], $aWords)){
                array_push($results, $bWords[$i]);
            }
        }
    }

    return $results;
}
© www.soinside.com 2019 - 2024. All rights reserved.