2
$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?

2 Answers 2

3

If you don't mind removing newlines, you can use this one:

<?php
$var = preg_replace('#.*?(<img.+?>).*?#is', '$1', $var);
Sign up to request clarification or add additional context in comments.

Comments

2

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]);

1 Comment

I think that he is trying to replace all content except <img> tags. This does the opposite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.