替换HTML标记中的图片src? [英] Replacing image src in HTML tags?

查看:666
本文介绍了替换HTML标记中的图片src?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式替换src html属性. HTML格式不正确,幸运的是,数据库中的所有页面都采用相同的形式-即

I want to use regex to replace src html attributes. The HTML is not malformed and fortunately takes the same form in all the pages in the database - i.e.

<img src="http://x.y/z/1.png" />

如果页面中只有一张图像,我的代码可以正常工作.我想知道替换多张图像的最佳方法,因为这将用相同的字符串替换所有图像标签.

I have code that works fine if there's only one image in the page. I want to know the best way to replace multiple images, as this one will replace all the image tags with the same string.

$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.pnghttp://x.y/a/2.png.

So if the page contains two files, one called 1.png and one called 2.png the script should parse the numbers and replace them with a different url such as http://x.y/a/1.png and http://x.y/a/2.png.

我听说preg_replace_callback是执行此操作的最佳方法,但是我不知道如何使它工作.帮助!

I've heard preg_replace_callback is the best way to do this but I have no idea how to get this working... Help!

推荐答案

解析器.这样可以节省很多时间和痛苦.

Don't use regular expressions for irregular languages like HTML. Use a parser instead. It will save you a lot of time and pain.

# Untested code:
$xml = new SimpleXml($xmlString);
foreach ($xml->xpath('//img') as $imgNode) {
    $imgNode->addAttribute('src', "http://x.y/a/" . $imgNode->getAttribute('src'));
}
echo $xml->asXML();

请注意,如果您需要使用 DOMDocument::loadHtml() 之类的东西, html不是xhtml(即有效的xml),但是想法仍然相同.

Note that you will need something like DOMDocument::loadHtml(), if your html is not xhtml (i.e. valid xml), but the idea remains the same.

这篇关于替换HTML标记中的图片src?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆