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

时间:2017-12-17 23:51:31

标签: php string-comparison

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

<?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
?>

2 个答案:

答案 0 :(得分: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 :(得分: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;
}