我有两个字符串
$string1 = 'Amateur developer | Photoshop lover| Alcohol scholar | Internet practitioner';
和
$string2 = 'Amateur developer | Photoshop lover| Alcohol scholar';
如何将这两个字符串PHP
与中间的特殊字符(空格和连字符)进行比较?
试试这个与案例进行比较;
$result = strcmp($string1, $string2);
试试这个进行比较,而不用考虑比较;
$result = strcasecmp($string1, $string2);
如果 $result 为 0(零),则字符串相等,否则两种情况都不同。
寻找这种比较?
<?php
$string1 = 'Amateur developer | Photoshop lover| Alcohol scholar | Internet practitioner';
$string2 = 'Amateur developer | Photoshop lover| Alcohol scholar';
if ($string1 == $string2) {
echo "Strings are same";
} else {
$stringArray1 = explode(' | ', $string1);
$stringArray2 = explode(' | ', $string2);
$diffAre = array_diff($stringArray1, $stringArray2);
echo "Difference in strings are " . implode($diffAre, ',');
}
?>
输出
Difference in strings are Internet practitioner
尝试这个
$result = strcmp($string1, $string2);
我建议使用 Jaccard 索引,请参阅:https ://gist.github.com/henriquea/540303
<?php
function getSimilarityCoefficient( $item1, $item2, $separator = "," ) {
$item1 = explode( $separator, $item1 );
$item2 = explode( $separator, $item2 );
$arr_intersection = array_intersect( $item2, $item2 );
$arr_union = array_merge( $item1, $item2 );
$coefficient = count( $arr_intersection ) / count( $arr_union );
return $coefficient;
}
$string2 = 'Amateur developer | Photoshop lover | Alcohol scholar | Internet practitioner';
$string2 = 'Amateur developer | Photoshop lover | Alcohol scholar';
echo getSimilarityCoefficient($string1,$string2,' | ');
?>
如果它们始终被管道 ( |
) 分开,而您只想要一个肮脏的检查:
// original strings
$str1 = 'Amateur developer | Photoshop lover| Alcohol scholar | Internet practitioner';
$str2 = 'Amateur developer | Photoshop lover| Alcohol scholar';
// split them by the pipe
$exp1 = explode('|', $str1);
$exp2 = explode('|', $str2);
// trim() them to remove excess whitespace
$trim1 = array_map('trim', $exp1);
$trim2 = array_map('trim', $exp2);
// you could also array_map them to strtolower
// to take CaSE out of the equation
然后:
// MATCHING ENTRIES
$same = array_intersect($trim1, $trim2);
var_dump($same);
// DIFFERENT ENTRIES
$diff = array_diff($trim1, $trim2);
var_dump($diff);
使用这个similar_text() - 计算两个字符串之间的相似度