我想用正则表达式来替换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