欢迎访问宙启技术站
智能推送

PHP中将HTML转换为纯文本格式的函数

发布时间:2023-06-30 10:11:24

在PHP中,可以使用strip_tags()函数将HTML代码转换为纯文本格式。

$text = '<h1>Example HTML</h1><p>This is an example of HTML code.</p>';

$plainText = strip_tags($text);
echo $plainText;

以上代码输出的结果为:

Example HTMLThis is an example of HTML code.

strip_tags()函数接受两个参数:要处理的字符串和可选的允许保留的HTML标记。如果不指定第二个参数,则默认删除所有HTML标记。

如果希望保留部分HTML标记,可以将这些标记作为第二个参数传递给strip_tags()函数。例如,如果希望保留<p>标记,可以这样写:

$text = '<h1>Example HTML</h1><p>This is an example of HTML code.</p>';

$plainText = strip_tags($text, '<p>');
echo $plainText;

以上代码输出的结果为:

This is an example of HTML code.

注意,strip_tags()函数只会删除HTML标记,而不会对其他文本内容进行任何处理。如果HTML代码中包含特殊字符或实体引用,这些字符将以原样显示在结果中。如果需要将实体引用转换为相应的字符,可以使用html_entity_decode()函数。

以下是将HTML文本转换为纯文本格式的完整示例代码:

$text = '<h1>Example HTML</h1><p>This is an example of <b>HTML</b> code with special characters like &#8230;</p>';

$plainText = strip_tags($text);
$decodedText = html_entity_decode($plainText);

echo $decodedText;

以上代码输出的结果为:

Example HTMLThis is an example of HTML code with special characters like …

通过使用strip_tags()函数和html_entity_decode()函数,可以将HTML转换为纯文本格式,并且处理特殊字符和实体引用。