6

私は次のような文字列を持っています

<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、php の実用的な解決策はありますか? ありがとう。

4

4 に答える 4

13

使用する:

<?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;

?>
于 2013-09-03T09:26:24.030 に答える
1

この関数は、改行を保持するように変更されています。

function strip($text,$keepLines=true)
{
    if($keepLines) $text=str_replace(array('</p>','<br/>','<br>'),array("</p> \n","<br/> \n","<br> \n"),$text);
    $text = strip_tags($text,"<style>");

    if(strpos($text,"<style")!==false && strpos($text,"</style>")!==false)
    {
        $substring = substr($text,strpos($text,"<style"),strpos($text,"</style>")+8);
        $text = str_replace($substring,'',$text);
    }

    if(!$keepLines)
    {
        $text = str_replace(array("\t","\r","\n"),"",$text);
        $text = preg_replace('/\s+/',' ',$text);
    }
    else
    {
        $text = str_replace('  ',' ',$text);
    }   
    return trim($text);
}
于 2020-04-30T17:38:59.210 に答える
-1

これは私にとってはうまくいきました。

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" ));
于 2018-03-09T17:27:19.737 に答える