php如何使用正则匹配去掉html

PhpPhp 2023-08-28 23:50:19 868
摘要: php使用正则匹配去掉html的方法:1、创建一个PHP示例文件;2、定义变量$html,包含HTML标签和文本;3、使用“preg_replace()”函数将所有HTML标签替换为空格,语法为“preg_replace('/(<[^>]+>| |\s+)/u','...

php使用正则匹配去掉html的方法:

1、创建一个PHP示例文件;

2、定义变量$html,包含HTML标签和文本;

3、使用“preg_replace()”函数将所有HTML标签替换为空格,语法为“preg_replace('/(<[^>]+>|&nbsp;|\s+)/u', ' ', $html)”;

4、使用内置函数“trim()”去掉字符串首尾空格,echo并输出结果即可。

代码示例如下

<?php
$html = '<p>这是一个带有HTML标签的文本。</p><a href="http://example.com">点击我</a>';
$clean_text = preg_replace('/(<[^>]+>|&nbsp;|\s+)/u', ' ', $html); // 替换所有HTML标签为空格
$clean_text = trim($clean_text); // 去除字符串首尾空格
echo $clean_text;
?>