PHP的strip_tags函数如何用
PHP的strip_tags函数如何用
`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>` 标签被保存,其他标签都被删除。
文章来源:丸子建站
文章标题:PHP的strip_tags函数如何用
https://www.wanzijz.com/view/87521.html