我正在研究一个使用php将HTML转换为纯文本版本的函数。我已经尝试了如下strip_tags()
,
$html='<style type="text/css">
@media only screen and (max-width: 480px) {
.message_mobile {
width: 100% !important;
}
}
</style>
<p class="message_mobile"> sample Text</p>';
$plain_text =strip_tags($html);
echo $plain_text;
但它会创建这样的输出,
@media only screen and (max-width: 480px) {
.message_mobile {
width: 100% !important;
}
}
sample Text
但我不需要标签<style>
内容。怎么做?而且我还有一个问题,当我尝试用表格剥离标签时,会产生不需要的线刹。如何解决这些问题?有没有从HTML创建纯文本的好方法?
使用此函数:
<?php
function strip_html_tags($str){
$str = preg_replace('/(<|>)'1{2}/is', '', $str);
$str = preg_replace(
array(// Remove invisible content
'@<head[^>]*?>.*?</head>@siu',
'@<style[^>]*?>.*?</style>@siu',
'@<script[^>]*?.*?</script>@siu',
'@<noscript[^>]*?.*?</noscript>@siu',
),
"", //replace above with nothing
$str );
$str = replaceWhitespace($str);
$str = strip_tags($str);
return $str;
} //function strip_html_tags ENDS
//To replace all types of whitespace with a single space
function replaceWhitespace($str) {
$result = $str;
foreach (array(
" ", " 't", " 'r", " 'n",
"'t't", "'t ", "'t'r", "'t'n",
"'r'r", "'r ", "'r't", "'r'n",
"'n'n", "'n ", "'n't", "'n'r",
) as $replacement) {
$result = str_replace($replacement, $replacement[0], $result);
}
return $str !== $result ? replaceWhitespace($result) : $result;
}
$html='<style type="text/css">
@media only screen and (max-width: 480px) {
.message_mobile {
width: 100% !important;
}
}
</style>
<p class="message_mobile"> sample Text</p>';
$plain_text = strip_html_tags($html);
echo $plain_text;
您可以使用类从 HTML 创建纯文本。
访问此链接,这可能会对您有所帮助。在 PHP 中将 HTML 转换为电子邮件的纯文本
课程: http://www.howtocreate.co.uk/php/html2texthowto.html
试试这个,它对我有帮助
http://code.google.com/p/iaml/source/browse/trunk/org.openiaml.model.runtime/src/include/html2text
你要找的函数是htmlspecialchars。
此代码:
<?php
$htmltag = '
<style type="text/css">
@media only screen and (max-width: 480px) {
.message_mobile {
width: 100% !important;
}
}
</style>
<p class="message_mobile"> sample Text</p>';
echo "<pre>".nl2br(htmlspecialchars($htmltag))."</pre>";
?>
将在您的网站上创建此输出:
<style type="text/css">
@media only screen and (max-width: 480px) {
.message_mobile {
width: 100% !important;
}
}
</style>
<p class="message_mobile"> sample Text</p>