开发者

preg_match_all how to remove img tag?

$str=<<<EOT
<img src="./img/upload_20571053.jpg" /><span>some word</span><div>some comtent</div>
EOT;

How to remove the img tag with preg_match_all or other way? Thanks.

I want echo <span>some开发者_如何学编程 word</span><div>some comtent</div> // may be other html tag, like in the $str ,just remove img.


As many people said, you shouldn't do this with a regexp. Most of the examples you've seen to replace the image tags are naive and would not work in every situation. The regular expression to take into account everything (assuming you have well-formed XHTML in the first place), would be very long, very complex and very hard to understand or edit later on. And even if you think that it works correctly then, the chances are it doesn't. You should really use a parser made specifically for parsing (X)HTML.

Here's how to do it properly without a regular expression using the DOM extension of PHP:

// add a root node to the XHTML and load it
$doc = new DOMDocument;
$doc->loadXML('<root>'.$str.'</root>');
// create a xpath query to find and delete all img elements
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//img') as $node) {
        $node->parentNode->removeChild($node);
}
// save the result
$str = $doc->saveXML($doc->documentElement);
// remove the root node
$str = substr($str, strlen('<root>'), -strlen('</root>'));


$str = preg_replace('#<img[^>]*>#i', '', $str);


preg_replace("#\<img src\=\"(.+)\"(.+)\/\>#iU", NULL, $str);
echo $str;

?


In addition to @Karo96, I would go more broad:

/<img[^>]*>/i

And:

$re = '/<img[^>]*>/i';
$str = preg_replace($re,'',$str);

demo

This also assumes the html will be properly formatted. Also, this disregards the general rule that we should not parse html with regex, but for the sake of answering you I'm including it.


Perhaps you want preg_replace. It would then be: $str = preg_replace('#<img.+?>#is', '', $str), although it should be noted that for any non-trivial HTML processing you must use an XML parser, for example using DOMDocument


$noimg = preg_replace('/<img[^>]*>/','',$str);

Should do the trick.


Don't use regex's for this. period. This isn't exactly parsing and it might be trivial but rexeg's aren't made for the DOM:

RegEx match open tags except XHTML self-contained tags

Just use DomDocument for instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜