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> 标签被保留,其他标签都被删除。