替换 HTML 标签中的图像 src?使用Regex从html字符串中提取所有图像

如果该页面包含两个文件,一个名为 1.png,一个名为 2.png,脚本应该解析数字并将它们替换为不同的 url,例如 http://vcncn.cn/a/1.png 和 <代码>http://vcncn.cn/a/2.png。

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

$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]);
    }
}

-------------------------------------

我需要从字符串中提取'gfx/image.png,它看起来像

<table cellpadding="0" cellspacing="0"  border="0" style="height:350px; margin:0; background: url('gfx/image.jpg') no-repeat;">
<table cellpadding="0" cellspacing="0" border="0" background="gfx/image.jpg" style=" width:700px; height:250px; "><tr><td valign="middle">

您可以使用以下正则表达式:(['"])([^'"]+\.jpg)\1然后获取组[2],这段代码运行良好:

var str = @"<table cellpadding=""0"" cellspacing=""0"" border=""0"" style=""height:350px; margin:0; background: url('gfx/image.jpg') no-repeat;""> <table cellpadding=""0"" cellspacing=""0"" border=""0"" background=""gfx/image.jpg"" style="" width:700px; height:250px; ""><tr><td valign=""middle"">"; var regex = new Regex(@"(['""])([^'""]+\.jpg)\1"); var match = regex.Match(str); while (match.Success) { Console.WriteLine(match.Groups[2].Value); match = match.NextMatch(); }

猜你喜欢

转载自blog.csdn.net/qikexun/article/details/130916114