2010-06-23 174 views
1

我想按以下方式替換頁面的鏈接位置(錨標記)。替換鏈接位置(href ='...')

樣品輸入:

text text text <a href='http://test1.com/'> click </a> text text 
other text <a class='links' href="gallery.html" title='Look at the gallery'> Gallery</a> 
more text 

樣本輸出

text text text <a href='http://example.com/p.php?q=http://test1.com/'> click </a> text text 
other text <a class='links' href="http://example.com/p.php?q=gallery.html" title='Look at the gallery'> Gallery</a> 
more text 

我希望我說清楚。無論如何,我正在嘗試使用PHP和reg-ex來做到這一點。你能否正確地點亮我?

謝謝 薩迪

+6

有些人遇到問題時會想:「我知道,我會用正則表達式。」現在他們有兩個問題。 – icktoofay 2010-06-23 05:46:20

+1

@icktoofay除非你是Jay-Z有99個問題:P – alex 2010-06-23 06:05:12

+1

如果你有更好的解決方案,然後reg-ex,請分享。我需要高效地解決問題。歡迎任何有效的解決方案。謝謝 – Sadi 2010-06-23 06:34:01

回答

9

不要使用正則表達式解析HTML。

是否使用PHP的內置XML解析引擎。它在你的問題上工作得很好(並回答引導問題):

<?php 
    libxml_use_internal_errors(true); // ignore malformed HTML 
    $xml = new DOMDocument(); 
    $xml->loadHTMLFile("http://stackoverflow.com/questions/3099187/replace-links-location-href"); 
    foreach($xml->getElementsByTagName('a') as $link) { 
    $link->setAttribute('href', "http://www.google.com/?q=" . $link->getAttribute('href')); 
    } 
    echo $xml->saveHTML(); // output to browser, save to file, etc. 
+0

謝謝。讓我測試它。但是另外一個HTML可能會變形(因此,我可能需要將它作爲libxml_use_internal_errors(false)使用;是不是?) – Sadi 2010-06-23 06:35:44

+1

libxml引擎實際上會修復無效嵌套標記,'libxml_use_internal_errors(false)'只會阻止PHP腳本從污染頁面輸出警告關於錯誤的HTML。 – leepowers 2010-06-23 06:59:34

+0

感謝+1解釋:) – Sadi 2010-06-23 09:56:07

-1

嘗試使用str_replace();

$string = 'your text'; 
    $newstring = str_replace ('href="', 'href="http://example.com/p.php?q=', $string); 
+0

:O !!!!爲什麼它會工作: -/ – Sadi 2010-06-23 09:55:08

+0

你可以檢查。 – pltvs 2010-06-24 07:59:47