从文本中删除图像

时间:2014-07-30 03:48:58

标签: php html preg-match-all

我有一些文字,我需要从这些文本中删除一些图像,我该怎么做?我想删除此图片:

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

Bug这个网站&#34; blabla.com&#34;可以改变,我有很多像这样的字符串:

<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" />

我需要一些像这样的php函数:getAllHtmlTagsFromText,而不是我要替换我要删除的img src。

我有这段代码来从文本中获取所有图像:

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

但是对于这一行,我只得到图像地址,如果我得到了像src / alt / class这样的所有属性,我可以从我的文本中删除图像。

1 个答案:

答案 0 :(得分:1)

几乎在那里,你有$matches数组,其中包含$post中img标签的所有匹配项。试试这个:

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

迭代每场比赛。

$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