2017-08-01 2 views
1

プレーンテキストのみを保持するために、すべてのhtmlタグを文字列から取り除く最良の方法を見つけようとしています。今では最も簡単な方法はstrip_tagsですが、壊れたタグなどではうまく動作しないので最適ではありません。私はDOM Parserが必要だと思います。しかし、私はこのことがどのように機能するかを知りません。PHPはすべてのhtmlタグを削除し、DOMパーサーでプレーンテキストを保持します

Some plain text 

私はそれをどのように操作を行うことができます。私は、DOMパーサを持つすべてのタグを除去し、プレーンテキストを維持したい

<p> 
     <strong>​ 
      Some plain text 
     </strong> 
    </p> 

:たとえば

iは、単純な文字列を持っていますか?私はのremoveChildを使用しようとしたが、それもテキストをすべて削除します。

$dom = new DOMDocument(); 
$dom->loadHTML($translation->text); 

foreach ($dom->getElementsByTagName("*") as $tag) { 
    $tag->parentNode->removeChild($tag); 
}; 
+1

'$ dom-> textContent' ...オリジナルの要素間空白をそのまま残すため、値をトリミングすることができます。 – CBroe

+0

php strip_tags関数を使用するhttp://php.net/manual/es/function.strip-tags.php – lucianov88

答えて

0

これを試してください:

<?php 

$content = <<<EOM 
    <p> 
    <strong> 
     Some plain text 
    </strong> 
    </p> 
EOM; 


$dom = new DOMDocument(); 
$dom->loadHTML($content); 

echo trim($dom->textContent); 

それとも、単に、strip_tags使用して、あなたがそれを行うことができます。

<?php 

$content = <<<EOM 
    <p> 
    <strong> 
     Some plain text 
    </strong> 
    </p> 
EOM; 

echo trim(strip_tags($content)); 
0

この機能は、簡単かつ迅速に使用:

function fetch_string($content) { 
    $content = preg_replace('@<script[^>]*?>.*?</script>@si', '', $content); 
    $content = preg_replace('@<style[^>]*?>.*?</style>@si', '', $content); 
    $content = strip_tags($content); 
    $content = trim($content); 
    return $content; 
} 

は、用法:

$string = '<p><strong>​Some plain text</strong></p>'; 
$output = fetch_string($string); 
0

あなたはこのためにHtmlPurifier使用することができます。試してください:

echo yii\helpers\HtmlPurifier::process($html); 

詳細については、linkを確認してください。

関連する問題