好了,回答你的問題,你有兩個選擇用正則表達式。
您可以將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