【问题标题】:Using RegEx to compare two strings for grouped differences in PHP在 PHP 中使用 RegEx 比较两个字符串的分组差异
【发布时间】:2011-06-16 17:33:17
【问题描述】:

所以我有两个字符串,我想比较并返回差异。我认为我不能使用简单的 preg_match() ,因为它返回一个包含所有差异的数组。

我在解释自己时遇到了一点麻烦,但我希望下面的例子能解决这个问题:

所以我有

String 1: AA **B** AA
String 2: AA **DA** AA

我希望返回类似于:

String2: 2 ==> DA

基本上我正在尝试检查 B 在 String1 中的位置和 DA 在 String 2 中的位置之间的关系

任何方向都将不胜感激,谢谢!

【问题讨论】:

标签: php regex string expression


【解决方案1】:

实际上,正则表达式不会为您执行此操作。您可以阅读 diff 如何在 http://en.wikipedia.org/wiki/Diff#Algorithm 上工作(这就是您想要的)。您可以使用这些算法创建一个执行简单diffs 的函数或类。

-- 编辑 1 Matt Ball 的好点子:Highlight the difference between two strings in PHP

【讨论】:

【解决方案2】:
$stringA = "hello world hello world helloo world";
$stringB = "hello php hello php hello php";

echo "string 1---->".$stringA."<br>";
echo "string 2---->".$stringB."<br>";

$array1 = explode(' ', $stringA);
$array2 = explode(' ', $stringB);

$result = array_diff($array2, $array1);

$zem= implode(' ',$result);
if (!empty($zem)) {
    echo "string diffrence---> ".$zem."<br>";
} else {
    echo "string diffrence--->both strings are same <br>";
}

$a = count(explode(' ', $stringA));
$b= count(explode(" ", $zem));

similar_text($stringA, $stringB , $p);
echo "  similarity between  the stirng is  Percent:".$p."% <br>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多