我想用正則表達式來替換src
html屬性。該HTML不是畸形的,幸運的是發生在數據庫中的所有頁面相同的形式 - 即替換HTML標籤中的圖像src?
<img src="http://x.y/z/1.png" />
我,如果有隻有一個頁面圖像工作正常代碼。我想知道替換多個圖像的最佳方法,因爲這將替換所有具有相同字符串的圖像標記。
$result = $s->db_query("SELECT reviewFullText as f FROM reviews WHERE reviewsID = 155");
while($row = mysql_fetch_array($result))
{
$body = stripslashes(html_entity_decode($row['f'], ENT_NOQUOTES, "UTF-8"));
preg_match_all('/<img.*?(src\=[\'|"]{0,1}.*?[\'|"]{0,1})[\s|>]{1}/i', $body, $matches);
for($i=0;$i<count($matches[0]);$i++)
{
$number = preg_replace("/[^0-9]/", '', $matches[0][$i]);
echo preg_replace('/<img.*?(src\=[\'|"]{0,1}.*?[\'|"]{0,1})[\s|>]{1}/i', '<img src="http://x.y/a/' . $number . '.png"', $matches[0][$i]);
}
}
因此,如果頁面包含兩個文件,一個叫1.png和一個叫2.png腳本應該分析這些數字,並用不同的URL,如http://x.y/a/1.png
和http://x.y/a/2.png
替換它們。
我聽說preg_replace_callback
是這樣做的最好方法,但我不知道如何得到這個工作......幫助!
相似的問題到http://stackoverflow.com/questions/1416425/preg-replace-preg-match-for-href-in-html-link – TrueWill 2009-09-13 16:56:42
可能的重複[你能提供一些例子,說明爲什麼它很難用正則表達式解析XML和HTML?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and -html-with-a-rege) – 2011-07-09 21:01:27
[RegEx match open tags but XHTML self-contained tags]可能重複(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml- self-contained-tags) – 2011-09-15 14:08:18