好了,回答你的问题,你有两个选择用正则表达式。
您可以将e
modifier用于正则表达式,它告诉preg_replace
替换为php代码并应执行。这通常被视为不是很大,因为它比EVAL真的没有更好的...
preg_replace($regex, "'href=\"http://{$host}?url='.urlencode('\\1').'\"'", $html);
其他选项(这是更好恕我直言)是使用preg_replace_callback
:
$callback = function ($match) use ($host) {
return 'href="http://'.$host.'?url='.urlencode($match[1]).'"';
};
preg_replace_callback($regex, $callback, $html);
但也永远不会忘记,don't parse HTML with regex ...
因此,在实践中,做(更强大的方式)的更好的办法,应该是:
$dom = new DomDocument();
$dom->loadHtml($html);
$aTags = $dom->getElementsByTagName('a');
foreach ($aTags as $aElement) {
$href = $aElement->getAttribute('href');
$href = 'http://'.$host.'?url='.urlencode($href);
$aElement->setAttribute('href', $href);
}
$html = $dom->saveHtml();
嗯正则表达式和HTML ... – kennytm 2010-08-24 12:19:15
哦,上帝......我们再次去... – Buggabill 2010-08-24 12:19:46
你愿意娱乐非正则表达式的解决方案吗? – salathe 2010-08-24 12:21:31