从字符串中删除img标记

时间:2015-03-14 15:07:26

标签: php image string-parsing

我有一个字符串$content,其中包含:

<p>Some random text <img class="alignnone" src="logo.png" alt="" width="1920" height="648"></p>

现在我要删除图片代码:

<img class="alignnone" src="logo.png" alt="" width="1920" height="648">

我尝试了strip_tags,但这已不再适用了。

$content = strip_tags($content, '<img></img>');

3 个答案:

答案 0 :(得分:1)

这是一个完整的工作示例。

<?php

$content = "<p>Some random text <img class=\"alignnone\" src=\"logo.png\" alt=\"\" width=\"1920\" height=\"648\"></p>";

echo strip_tags($content,"<p>");

?>

答案 1 :(得分:0)

如果<p></p>是您唯一拥有的其他代码,则可以使用strip_tags这样的代码:

$content = strip_tags($content, '<p></p>');

如果您想要保留其他标记,只需将它们添加到strip_tags的第二个参数

您还可以使用字符串函数的组合来实现此目的:

$count = substr_count($c, '<img ');
while($count >= 1){

    $i = strpos($c, '<img ');
    $j = strpos($c, '>',$i)+1;
    $c = substr($c, 0,$i) . substr($c,$j);

    $count--;
}
echo $c;

这也需要处理多个<img>代码

答案 2 :(得分:-1)

您可以使用strpos() - 函数搜索img-Tags: http://www.w3schools.com/php/func_string_strpos.asp

一旦知道了字符串中的开始和结束位置,就可以使用substr() - 函数访问所需的部分: http://php.net/manual/de/function.substr.php

在你的例子中:

$left = strpos($content,'<img');
//$left should now be "20"
//to find the closing >-tag you need the string starting from <img... so you assign that to $rest:
$rest = substr($content,(strlen($content)-$left+1)*(-1));
$right = strpos($rest,">")+$left;
//now you know where the img ends so you can get the string surrounding it with:
$surr = substr($content,0,$left).substr($content,(strlen($content)-$right)*(-1));

编辑:经过测试,可用于删除第一个img-Tag

相关问题