php html转换成文本的方法:首先,创建一个php样本文件;然后用“function html2text($str){...}".
本文的运行环境:Windows7系统,PHP 7.1版本,DELL G3电脑。
Php将HTML转换成txt文本的功能。
使用php的preg_replace函数替换html中的标签。
代码:
function html2text($str){
$str = preg_replace("/<style .*?<\/style>/is", "", $str); $str = preg_replace("/<script .*?<\/script>/is", "", $str);
$str = preg_replace("/<br \s*\/?\/>/i", "\n", $str);
$str = preg_replace("/<\/?p>/i", "\n\n", $str);
$str = preg_replace("/<\/?td>/i", "\n", $str);
$str = preg_replace("/<\/?div>/i", "\n", $str);
$str = preg_replace("/<\/?blockquote>/i", "\n", $str);
$str = preg_replace("/<\/?li>/i", "\n", $str);
$str = preg_replace("/\ \;/i", " ", $str);
$str = preg_replace("/\ /i", " ", $str);
$str = preg_replace("/\&\;/i", "&", $str);
$str = preg_replace("/\&/i", "&", $str);
$str = preg_replace("/\<\;/i", "<", $str);
$str = preg_replace("/\</i", "<", $str);
$str = preg_replace("/\&\;/i", '"', $str);
$str = preg_replace("/\&/i", '"', $str);
$str = preg_replace("/\&lsquo\;/i", "'", $str);
$str = preg_replace("/\&lsquo/i", "'", $str);
$str = preg_replace("/\&rsquo\;/i", "'", $str);
$str = preg_replace("/\&rsquo/i", "'", $str);
$str = preg_replace("/\>\;/i", ">", $str);
$str = preg_replace("/\>/i", ">", $str);
$str = preg_replace("/\&\;/i", '"', $str);
$str = preg_replace("/\&/i", '"', $str);
$str = strip_tags($str);
$str = html_entity_decode($str, ENT_QUOTES, $encode);
$str = preg_replace("/\&\#.*?\;/i", "", $str);
return $str;
}推荐学习:PHP视频教程
以上是php html如何转换成文本的细节。更多详情请关注AdminJS的其他相关文章!