我遇到了以下脚本的问题,该脚本通过用匹配替换它们来添加指向文本块的链接。
它完美适用于它的设计目的,创建车辆ID的链接,但我想将其更改为车辆名称,问题是脚本重新读取被替换的文本并覆盖它。
是否可以忽略超链接中的文本?
// The following script was written by Walkerneo
function replaceLinks($replacements, $string){
foreach($replacements as $key=>$val){
$key=strtolower((string)$key);
$newReplacements[$key]=array();
$newReplacements[$key]['id']=$val;
$newReplacements[$key]['b']=array();
$newReplacements[$key]['a']=array();
foreach($replacements as $key2=>$val2){
$key2=(string)$key2;
$b = ($key=='11 22'&&$key2=='11 22 33');
if($b){
l('strlen $key2: '.strlen($key2));
l('strlen $key: '.strlen($key));
l('strpos: '.(strpos($key2,$key)));
}
if(strlen($key2)>strlen($key) && ($pos=strpos($key2,$key))!==false){
if($pos!=0){
$newReplacements[$key]['b'][]=substr($key2,0,$pos);
}
if(($end=$pos+strlen($key))!=strlen($key2)){
$newReplacements[$key]['a'][]=substr($key2,$end);
}
}
}
}
foreach($newReplacements as $key=>$item){
$tmp="/(?<![\w>])";
foreach($item['b'] as $b){
$tmp.="(?<!$b)";
}
$tmp.="($key)";
foreach($item['a'] as $a){
$tmp.="(?!$a)";
}
$tmp.='/ie';
$replacementMatches[]=$tmp;
}
return preg_replace($replacementMatches,'"<a href=\"".$newReplacements[strtolower("$1")]["id"]."\">$1</a>"' ,$string);
}
//$replaceWith = array('ford mustang'=>123,'ford'=>42,'honda'=>324); <-- this is what the script was written for
$replaceWith = array('ford mustang'=> 'make=Ford&model=Mustang','ford'=> 'make=Ford','honda'=> 'make=Honda');
$string = "That is a very nice ford mustang, if only every other ford was quite as nice as this honda";
echo replaceLinks($replaceWith,$string);