strip_tags 函數用于從給定字符串中去除 HTML 和 PHP 標簽,并返回去除標簽后的結果。
以下是使用 strip_tags 函數的基本語法:
php
string strip_tags ( string $str [, string $allowable_tags ] )
參數解釋:
- $str:必需,要處理的字符串。
- $allowable_tags:可選,指定允許保留的標簽。如果提供了此參數,strip_tags 函數將僅保留指定的標簽,其他標簽
都會被刪除。
示例用法:
php
$html = "<h1>Hello</h1><p>This is a paragraph.</p><script>alert('Hello');</script>";
$filteredText = strip_tags($html);
echo $filteredText;
輸出結果將是:Hello This is a paragraph. alert('Hello');
在上面的示例中,strip_tags 函數將 <h1>、<p> 和 <script> 標簽從字符串中去除,只保留文本內容。
如果您想保留特定的標簽,可以使用第二個可選參數 $allowable_tags。例如:
php
$html = "<h1>Hello</h1><p>This is a paragraph.</p><script>alert('Hello');</script>";
$filteredText = strip_tags($html, "<h1><p>");
echo $filteredText;
輸出結果將是:<h1>Hello</h1><p>This is a paragraph.</p>
在上面的示例中,只有 <h1> 和 <p> 標簽被保留,其他標簽都被刪除。