在PHP中,你可以使用正则表达式来去掉HTML标签。通常可以使用 preg_replace 函数来实现这个功能。以下是一个简单的示例代码,展示如何使用正则表达式去掉HTML标签:
<?php
// 示例HTML内容
$html = "<div><p>This is a <b>sample</b> text.</p></div>";
// 使用正则表达式去掉HTML标签
$text = preg_replace('/<[^>]*>/', '', $html);
// 输出结果
echo $text;
?>
preg_replace 函数用于执行正则表达式的搜索和替换。/<[^>]*>/ 的含义是:
< 匹配HTML标签的开始。[^>]* 匹配任意数量的非 > 字符(即标签内的内容)。> 匹配HTML标签的结束。'',即去掉所有匹配的HTML标签。This is a sample text.
DOMDocument 类。DOMDocument 的示例:<?php
// 示例HTML内容
$html = "<div><p>This is a <b>sample</b> text.</p></div>";
// 创建DOMDocument对象
$dom = new DOMDocument();
// 加载HTML内容
@$dom->loadHTML($html);
// 获取纯文本内容
$text = $dom->textContent;
// 输出结果
echo $text;
?>
这种方法更加健壮,能够处理更复杂的HTML结构。