[英]PHP preg_replace text only if in href attribute
<a href="http://www.example.com/foo/bar/" title="foo">
<img src="http://www.example.com/foo/bar/" alt="foo" />
</a>
我如何只在href屬性中preg_replace foo一詞?
注意:頁面上有多個鏈接。
您可以這樣做:
$str = preg_replace('/(href="[^"]*)foo/', '$1replacement', $str);
或者,您可以使用后向:
$str = preg_replace('/(?<=href="[^"]*)foo/', 'replacement', $str);
需要注意的是,如果沒有這只會工作'
-delimited屬性和沒有逃脫"
屬性中加入。
這就是為什么您應該真正考慮使用DOM解析器,而不是使用正則表達式來處理HTML的原因。
更新:這是使用解析器的正確實現(我剛剛選擇了PHP Simple HTML DOM解析器,因為它是第一個出現在Google上的解析器):
require "simple_html_dom.php";
$html = file_get_html($filename);
foreach($html->find('a') as $element)
{
$element->href = preg_replace('/foo/', 'replacement', $element->href);
}
現在echo
$html
或將其保存到文件中,將包含正確替換的HTML。 (使用DOM解析器很容易。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.