[英]Tidy up an image tag
我有这个图像标签,我从一个有错误的天气来源,输出不是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
但我似乎无法让它工作,任何想法?
如果HTML总是具有完全相同的语法问题,那么这将删除<img
和src=
之间的任何内容。 如果HTML结构发生变化,这很容易破解,但因为它已经破碎了......
$html = preg_replace('/(?<=<img ).*?(?=src=)/', '', $horribleHorribleHTML);
它没有经过测试,但应该这样做。
<?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;
?>
您可以尝试匹配要从输入中保存的属性,您可以尝试首先获取看起来像<img>
标记的部分,然后挑选属性,查看您感兴趣的部分:
$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";
}
这个 :
$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 />
标记没有改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.