2016-04-04 60 views
0

有沒有辦法阻止從數據庫表中輸出img-elements?數據庫輸出阻止圖像

在我的數據庫是一些HTML的代碼存儲:

表:TEST_TABLE
場:代碼

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

現在我輸出數據庫內容:

$code = $db->getValue('code'); 

<?php echo $code ?> 

輸出code字段的完整內容。我想阻止<img> -element的輸出。

回答

2

您可以用兩種方式做它。首先,其他人建議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> 
+0

'''strip_tags()'''是去這裏的路。它比'''preg_match()'''更安全。切勿使用正則表達式解析HTML。 –

+0

工作正常!謝謝Tomasz! – susanloek

-2

您可能需要使用preg_replace才能使用它,它將從字符串中將所有<img>替換爲space

,如果你想與任何其他的東西來代替,修改$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; 

Example Demo

使用與您的代碼:

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

爲什麼向下投票?應該提到理由。 – Noman

+0

這是你的理由:https://3v4l.org/gS9MX - 正則表達式不應該用於解析HTML。 –

0

你可以做到這一點使用CSS。

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

<?php echo $code ?> 
</div> 

CSS

#content img{display:none;} 

OR

jQuery的

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

超級簡單... – Chay22