所以我有这个php变量:
$keywords = array("google"=>"http://google.com","stackoverflow"=>"http://stackoverflow.com");
$content = "<p>Hello Stackover flow</p>
<p><img src='IMG_URL' alt='stackoverflow logo'/></p>
<p>Let's go to <a href='http://stackoverflow.com'>stackoverflow</a></p>
<p>To use stackoverflow and google</p>";
如何将其转换为:
$content = "<p>Hello Stackover flow</p>
<p><img src='IMG_URL' alt='stackoverflow logo'/></p>
<p>Let's go to <a href='http://stackoverflow.com'>stackoverflow</a></p>
<p>To use <a href='http://stackoverflow.com'>stackoverflow</a> and <a href="http://google.com">google</a></p>";
答案 0 :(得分:0)
建议您使用array_map()
&amp; implode()
。例如:
$keywords = array("google"=>"http://google.com","stackoverflow"=>"http://stackoverflow.com");
$content = "<p>Hello Stackover flow</p>
<p><img src='IMG_URL' alt='stackoverflow logo'/></p>
<p>Let's go to <a href='http://stackoverflow.com'>stackoverflow</a></p>
<p>To use stackoverflow and google</p>";
$anchors = array_map(function($v, $k){
return '<a href="'.$v.'">'.$k.'</a>';
}, $keywords, array_keys($keywords));
$anchors = '<p> To use '.implode(' and ', $anchors).'</p>';
echo preg_replace("/<p>To use (.*?)<\/p>/", $anchors, $content);
<强>参考:强>