PHP strip_tags

PHP strip_tags 函式可以將字串中所包含的 HTMLPHP 標籤消除,也可以依照當時的需求自行設定不被消除的保留標籤,讓輸出結果更加的彈性。strip_tags 函式用來消除標籤,其效果與 htmlspecialchars 用來轉換標籤並不相同。

PHP strip_tags 基本語法

String strip_tags( $string , $allowable_tags )


strip_tags 函式小括號內的第一個參數 $string 是必填項目,即要被處理的字串,第二個參數 $allowable_tags 是選擇項目,不一定要填寫,他的功能是用來設定哪些標籤要保留,有設定的標籤將被 strip_tags 函式保留,但註解一定會被消去。

PHP strip_tags 範例參考
<?php
$string_1 = '<p>Welcome to wibibi.</p><a href="#">Test link.</a><!-- 這裡是註解 --> ';
echo strip_tags($string_1).'<br>';
$string_2 = '<p>Welcome to wibibi.</p><a href="#">Test link.</a><!-- 這裡是註解 --> ';
echo strip_tags($string_2,'<p><a>');
?>
以上輸出結果如
Welcome to wibibi.Test link.

Welcome to wibibi.

Test link.
如果檢視網頁原始檔可以看到這樣的結果


網頁原始檔中的 <br> 標籤,左邊是輸出 strip_tags($string_1) 結果,未設定任何保留標籤,所以原則上所有的 HTML 標籤都被消除,<br> 標籤右邊則是輸出保留了 <p> 與 <a> 標籤完整功能的結果,所以呈現出段落以及超連結的效果。

相關主題研究
© Copyright wibibi.com 網頁設計教學百科 基礎的網頁設計規劃、資料庫與程式設計 Since 2012