PHP - 从字符串中删除 <img> 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1107194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:06:34  来源:igfitidea点击:

PHP - remove <img> tag from string

phpstring

提问by Mike

Hey, I need to delete all images from a string and I just can't find the right way to do it.

嘿,我需要从字符串中删除所有图像,但我找不到正确的方法。

Here is what I tryed, but it doesn't work:

这是我尝试过的,但不起作用:

preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;

Any ideas?

有任何想法吗?

回答by Sean Bright

Try dropping the \in front of the >.

尝试将\放在>.

Edit: I just tested your regex and it works fine. This is what I used:

编辑:我刚刚测试了你的正则表达式,它工作正常。这是我使用的:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

The result is:

结果是:

this is something with an (image)  in it.

回答by John Kugelman

You need to assign the result back to $contentas preg_replacedoes not modify the original string.

您需要将结果分配回$contentaspreg_replace不修改原始字符串。

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

回答by Ben S

I would suggest using the strip_tagsmethod.

我会建议使用该strip_tags方法。

回答by Yunieskid

Sean it works fine i've just used this code

肖恩它工作正常我刚刚使用了这个代码

$content = preg_replace("/<img[^>]+\>/i", " ", $content); 
echo $content;

//the result it's only the plain text. It works!!!

//结果只是纯文本。有用!!!

回答by Laura Murray

I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!

我想显示新闻故事的前 300 个单词作为预览,不幸的是,这意味着如果一个故事在前 300 个单词内有图像,那么它会显示在预览列表中,这确实与我的布局混乱。我使用上面的代码隐藏了从我的数据库中获取的字符串中的所有图像,它运行得非常好!

$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news); 
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
} 
else { 
echo $news; 
}

回答by solihin al mujahidin

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

如果用户输入

<img src="#">

In the database table just insert character this #

在数据库表中插入字符这个#

Works for me

为我工作

回答by loro

simply use the form_validation class of codeigniter:

只需使用 codeigniter 的 form_validation 类:

strip_image_tags($str).

$this->load->library('form_validation');
$this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');