Reputation: 33
$var = "text<img src='/img/tag1.gif' alt='' />
text text text text text <i>-blah-blah-blah-blah-blah-blah</i>
<img src='/img/tag2.gif' alt='' />
<img src='/img/myhome.gif' alt='' />
<b>text</b> text text blah-blah-blah-blah-blah-blah-blah-blah
<img src='/img/age.gif' alt='' />";
$var = preg_replace('/(<img(.+?)>)/i', '', $var);
echo $var;
How do I in this text replace all text content except IMG tags?
Upvotes: 2
Views: 2702
Reputation: 145482
To strip any non-img tags PHPs strip_tags()
would easier:
$var = strip_tags($var, "<img>");
Removing just text is cumbersome, and it's much easier to extract than remove in this case:
preg_match_all('#<img\b[^>]*>#', $var, $match);
$var = implode("\n", $match[0]);
Upvotes: 2
Reputation: 1467
If you don't mind removing newlines, you can use this one:
<?php
$var = preg_replace('#.*?(<img.+?>).*?#is', '$1', $var);
Upvotes: 3