eugui
eugui

Reputation: 471

Remove images from text

I have some texts and I need to remove some images from these texts, how can I do this? I wnat to remove this image:

<img src="//blabla.com/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley" />

Bug this site "blabla.com" can change, I have a lot of strings like this one:

<img src="http://www.bleble.com/wp-includes/images/smilies/icon_hap.gif" alt=":)" class="wp-smiley" />
<img src="http://www.blublu.com/wp-includes/images/smilies/icon_bor.gif" alt=":(" class="wp-smiley" />

I need some php function like this: getAllHtmlTagsFromText than I will replace the img src that I want to remove.

I have this code to get all the images from text:

$output = preg_match_all("/<img .*?(?=src)src=\"([^\"]+)\"/si", $post, $matches);

But with this line I get only the image address and If I get all the attributes like src/alt/class I can remove the image from my texts.

Upvotes: 0

Views: 481

Answers (1)

Juank
Juank

Reputation: 6196

Almost there, you have the $matches array that has all the matches to img tags in $post. Try this:

// change the regex to match any "<img " followed by anything except a ">", lastly the closing ">"
$output = preg_match_all("/<img [^>]+>/si", $post, $matches);

The iterate over every match.

$matches = $matches[0]; // due to the way preg_match populates the $matches array
foreach ($matches as $i => $match){
    $post = str_replace($match, '', $post);
}

echo $post; // this should now print everything except the <img> tags

Upvotes: 1

Related Questions