php - 如果通过比较字符串发现中间的子字符串被删除,如何突出显示下一个和上一个子字符串?

标签 php string comparison

我正在比较 PHP 中的两个字符串。在修改后的新字符串中,我正在编写代码来突出显示与旧字符串相比的更改。但我卡在这里。

例如:

旧字符串:这是我的内容。

新字符串:这是我的内容。

在这方面,我想要这样的东西。

新字符串:这里是我的内容。

我尝试通过保存以前的单词来匹配单词。但没有任何效果。

class ContentController extends Controller
{ 
 public function diffArray($old, $new){
    $matrix = array();
    $maxlen = 0;
    foreach($old as $oindex => $ovalue){
        $nkeys = array_keys($new, $ovalue);
        foreach($nkeys as $nindex){
            $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ? $matrix[$oindex - 1][$nindex - 1] + 1 : 1;
            if($matrix[$oindex][$nindex] > $maxlen){
                $maxlen = $matrix[$oindex][$nindex];
                $omax = $oindex + 1 - $maxlen;
                $nmax = $nindex + 1 - $maxlen;
            }
        }
    }
    if($maxlen == 0) return array(array('d'=>$old, 'i'=>$new));
    return array_merge(
        self::diffArray(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)),
        array_slice($new, $nmax, $maxlen),
        self::diffArray(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen)));
}

public function htmlDiff($old, $new){
    $ret = '';
    $diff = self::diffArray(explode(' ', $old), explode(' ', $new));
    foreach($diff as $k){
        if(is_array($k)){
            $ret .= /*(!empty($k['d'])?'<del style="background-color:#ffcccc">'.implode(' ',$k['d']).'</del> ':'').*/(!empty($k['i'])?'<span style="background-color:#ccffcc">'.implode(' ',$k['i']).'</span> ':'');
        }else{
            $ret .= $k . ' ';
        }
    }
    return $ret;
}

$old_content = "Here is the my content";
$new_content = "Here is my content";
$highlighted_content = ContentController::htmlDiff($old_content, $new_content);

}

最佳答案

试试这个:

Nb : I didn't prevent my code from notice error, please make sure keys are define

$old = " Here is the my content";
$new = " Here is my content";

$old_exp = explode(' ',$old);
$new_exp = explode(' ',$new);

$del_key=array_keys((array_diff($old_exp, $new_exp)));
var_dump($del_key);

foreach($del_key as $old_key){
    $new_exp[$old_key-1]="<b>".$new_exp[$old_key-1]."</b>";
    $new_exp[$old_key]="<b>".$new_exp[$old_key]."</b>";
}

$new_str = implode(" ", $new_exp);
echo $new_str;

希望对你有帮助

玩得开心:)

关于php - 如果通过比较字符串发现中间的子字符串被删除,如何突出显示下一个和上一个子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57323800/

相关文章:

php - 在双引号中使用变量名是坏习惯吗?

php - 使用PHPExcel将数据从mysql导出到xls

java - 如何获取包含在指定字符串中的特定字符串?

comparison - 仅复制差异(kdiff、winmerge、任何类似工具的差异)

java - compare() 中的空字段怎么办?

algorithm - 在 DWORD 数组中查找最重要的 DWORD

php - 查找字符串中重叠的所有子字符串

php - 仅一对一关系的查找表?

php - 如何从用 print_r 打印的数组的输出创建一个数组?

c# - 使用 Regex .NET 样式的变量扩展