我正在比较 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/