我正在努力做到这一点:
<span class="introduction">
<img alt="image" src="/picture.jpg" />
</span>
转换成这个:
<img alt="image" src="/picture.jpg" />
我如何使用正则表达式执行此操作?也就是说,如何从给定的html字符串中提取img-tag?
注意:在介绍标签中可以有更多的html但只有一个img-tag
答案 0 :(得分:9)
你不应该在HTML上使用正则表达式,那么:?
$string = '<span class="introduction"><img alt="image" src="/picture.jpg" /></span>';
echo strip_tags($string, '<img>');
否则我会使用HTML / XML解析器
答案 1 :(得分:6)
怎么样
"<img[^>]*>"
尝试使用grep
kent$ echo '<span class="introduction">
quote> <img alt="image" src="/picture.jpg" />
quote> </span>
quote> '|grep -P "<img[^>]*>"
<img alt="image" src="/picture.jpg" />
答案 2 :(得分:5)
preg_match('#(<img.*?>)#', $string, $results);
应该有效,导致$results[1]
答案 3 :(得分:1)
//span[@class="introduction"]/img
查找所有img元素,这些元素是任何span元素的直接子元素,其class属性为introduction。
答案 4 :(得分:0)
我来到这个解决方案
/<img ([^>"']*("[^"]*"|'[^']*')?[^>"']*)*>/
在
上测试 <other html elements like span or whatever><img src="asd>qwe" attr1='asd>qwe' attr2='as"dqwe' attr3="as'dqwe" ></other html elements like span or whatever>