我有
之类的字符串<p>
<style type="text/css">
P { margin-bottom: 0.21cm; direction: ltr; color: rgb(0, 0, 0); }P.western { font-family: "Times New Roman",serif; font-size: 12pt; }P.cjk { font-family: "Arial Unicode MS",sans-serif; font-size: 12pt; }P.ctl { font-family: "Tahoma"; font-size: 12pt; } </style>
</p>
<p align="CENTER" class="western" style="margin-bottom: 0cm">
<font size="5" style="font-size: 20pt"><u><b> TEXT I WANT TO GET </b></u></font></p>
如何删除html,css并仅获取文本?
我知道strip_tags()
,我可以用preg_replace
编写函数,但有没有一个可行的解决方案?
感谢。
答案 0 :(得分:10)
使用:
<?php
$text = '<p>
<style type="text/css">
P { margin-bottom: 0.21cm; direction: ltr; color: rgb(0, 0, 0); }P.western { font-family: "Times New Roman",serif; font-size: 12pt; }P.cjk { font-family: "Arial Unicode MS",sans-serif; font-size: 12pt; }P.ctl { font-family: "Tahoma"; font-size: 12pt; } </style>
</p>
<p align="CENTER" class="western" style="margin-bottom: 0cm">
<font size="5" style="font-size: 20pt"><u><b> TEXT I WANT TO GET </b></u></font></p>';
$text = strip_tags($text,"<style>");
$substring = substr($text,strpos($text,"<style"),strpos($text,"</style>")+2);
$text = str_replace($substring,"",$text);
$text = str_replace(array("\t","\r","\n"),"",$text);
$text = trim($text);
echo $text;
?>
答案 1 :(得分:0)
这对我有用。
function strip_tag_css($text){
$text = strip_tags($text,"<style>");
$substring = substr($text,strpos($text,"<style"),strpos($text,"</style>")+2);
$text = str_replace($substring,"",$text);
$text = str_replace(array("\t","\r","\n"),"",$text);
$text = trim($text);
return $text;
}
$bodymensage = str_replace(' ','',html_entity_decode( strip_tag_css(strip_tags($message)), ENT_QUOTES, "utf8" ));
答案 2 :(得分:0)
要确保删除样式标签,并将所有空格减少到单个空格:
$text = '<p>
<style type="text/css">
P { margin-bottom: 0.21cm; direction: ltr; color: rgb(0, 0, 0); }P.western { font-
family: "Times New Roman",serif; font-size: 12pt; }P.cjk { font-family: "Arial Unicode
MS",sans-serif; font-size: 12pt; }P.ctl { font-family: "Tahoma"; font-size: 12pt; }
</style>
</p>
<p align="CENTER" class="western" style="margin-bottom: 0cm">
<font size="5" style="font-size: 20pt"><u><b> TEXT I WANT TO GET </b></u></font>
</p>
<style>a { color: red}</style>';
$text = strip_tags($text, '<style>');
$start = strpos($text, '<style');
// All of occurrences of <style>.
while ($start !== false) {
$end = strpos($text, '</style>');
if (!$text) {
break;
}
$diff = $end - $start + strlen('</style>');
$substring = substr($text, $start, $diff);
$text = str_replace($substring, '', $text);
$start = strpos($text, '<style');
}
// Remaining <style> if any.
$text = strip_tags($text);
// Remove all new lines and tabs and use a space instead.
$text = str_replace(["\n", "\r", "\t"], ' ', $text);
// Trim left and right.
$text = trim($text);
// Remove all spaces that have more than one occurrence.
$text = preg_replace('!\s+!', ' ', $text);
echo $text;
这里是output。
答案 3 :(得分:0)
已修改此功能以保留换行符。
shortest = minimumBy (comparing length)