如何在 PHP 中比较带有特殊字符的字符串


How to compare strings with special characters in PHP?

我有两个字符串

$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(零(,则字符串相等,否则在两种情况下都不相等。

我建议使用Jaccard Index,请参阅以下内容: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(( - 计算两个字符串之间的相似性

寻找这种比较?

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