PHP 如何比较两个变量之间的字符串并只显示唯一的字符串?
PHP how to compare strings between two variables and display only unique strings?
注意: 这里是 S.O。 有很多方法可以做到这一点 使用数组键,在相同变量的 values/words 之间,在两个不同的数组之间,但我在互联网上看不到字符串和数组之间的任何内容两个不同的变量。
<?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
?>
正如 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)));
}
<?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;
}
注意: 这里是 S.O。 有很多方法可以做到这一点 使用数组键,在相同变量的 values/words 之间,在两个不同的数组之间,但我在互联网上看不到字符串和数组之间的任何内容两个不同的变量。
<?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
?>
正如 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)));
}
<?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;
}