2010-08-24 49 views
1

我想解析PHP中的所有鏈接在PHP文件中的這種方式:替換href ='LINK'爲href ='MY_DOMAIN?URL = LINK',因爲LINK會是url參數,它必須是urlencoded。我試着這樣做:preg_replace在替換中應用字符串函數(如urlencode)

preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html); 

但「$ {1}」只是字符串文字,而不是建立在預浸網址,有什麼需要我做什麼,使這個代碼的工作?

+3

嗯正則表達式和HTML ... – kennytm 2010-08-24 12:19:15

+2

哦,上帝......我們再次去... – Buggabill 2010-08-24 12:19:46

+0

你願意娛樂非正則表達式的解決方案嗎? – salathe 2010-08-24 12:21:31

回答

10

好了,回答你的問題,你有兩個選擇用正則表達式。

您可以將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(); 
+0

只需$ aElement-> setAttribute($ href);必須替換$ aElement-> setAttribute('href',$ href); – hippout 2010-08-24 14:12:27

+0

哎呀,感謝您注意到... – ircmaxell 2010-08-24 14:23:08