1

我有这个图像标签,我从一个有错误的天气源获得,输出不是 html 而是 wml/wap,所以当它出现时它会崩溃并烧毁。图片标签是这样出现的:

<img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >" src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>

我希望它是这样的:

<img src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>

我知道我必须使用preg_replace,但我似乎无法让它工作,有什么想法吗?

4

4 回答 4

1

如果 HTML 总是有完全相同的语法问题,这将有助于删除 和 之间的任何<img内容src=。如果 HTML 结构发生变化,这很容易被破坏,但因为它已经被破坏了......

$html = preg_replace('/(?<=<img ).*?(?=src=)/', '', $horribleHorribleHTML);
于 2012-09-03T14:17:34.860 回答
1

这个 :

$imgTag = '<img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >" src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>';
$returnValue = preg_replace('/(<img)(.*)(src.*)/', '$1 $3',$imgTag);

将输出:

'<img src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>'

假设您的格式错误的<img />标签没有改变。

于 2012-09-03T14:23:03.457 回答
1

It's not tested, but this should do it.

<?php
$sStr = '<img ... your image>'; // your string
$iStart = strpos('src="', $sStr); // find the src
$iEnd = strpos('"', $sStr, $iStart); // find the end
$sURL = substr($sStr, $iStart, $iEnd); // get the image
echo $sURL;
?>
于 2012-09-03T14:18:31.727 回答
1

You can try to match on the attributes you want to save from your input, you can try to get the parts that look like an <img> tag first, and then cherry-pick the attribute looking parts of them you are interested in:

$input = 'some other content
    <img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >"
        src="http://www.vremea.com/images/fogshow.gif"  width="50" height="50"/>
        <span class="some"> more other content
    </span>

    <img alt="FACE="Monospace,Courier">LRPatches, Sky clear, Q1020</FONT><Mist, >"
        src="http://www.vremea.com/images/fogshow.gif"
        width="50"
        height="50"/> <span class="some"> more other content
    ';
preg_match_all('/<img.+?\/>/sim', $input, $img_parts);
foreach ($img_parts[0] as $img_part) {
    $attrs = array();
    preg_match_all('/(?<key>src|width|height)\s*=\s*"(?<value>[^"]+)/i', $img_part, $m);
    foreach ($m['key'] as $i => $key) {
        $attrs[] = "{$key}=\"{$m['value'][$i]}\"";
    }
    print "<img ".join(' ', $attrs)." />\n";
}
于 2012-09-03T14:18:39.947 回答