数据库输出阻止图像


Database output prevent images

有没有办法防止img元素从数据库表中输出?

在我的数据库中存储了一些HTML代码:

表:test_Table
字段:代码

<p>This is simple test!</p><img src="files/test.img">

现在我正在输出数据库内容:

$code = $db->getValue('code');
<?php echo $code ?>

输出code字段的完整内容。我想阻止<img>-元素的输出。

您可以通过两种方式来实现它。首先,其他人建议使用preg_replace(),或者使用strip_tags()和allowable_tags参数来定义允许的标签。如果您的输出包含其他您不想回显的标记,那么您是安全的。

文档示例:

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "'n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');

上面的例子将输出:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

您可以使用css来实现这一点。

<div id="content">
$code = $db->getValue('code');
<?php echo $code ?>
</div>

CSS

#content img{display:none;}

jQuery

$(function(){
   $('#content img').remove();
});

您可能需要使用preg_replace,它将用字符串中的space替换所有<img>

如果要替换为其他内容,请修改$replaceWith

 $content = '<p>This is simple test!</p><img src="files/test.img"><img src="files/test.img">';
    $replaceWith = " "; 
    $content = preg_replace("/<img[^>]+'>/i", $replaceWith, $content); 
    echo $content;

示例演示

代码用法:

$code = $db->getValue('code');
$content = preg_replace("/<img[^>]+'>/i", " ", $code); 
echo $content;