strip_tags、html タグを取り除く PHP の関数

当たり前のことでも書いていくといいことがあるはずなので備忘録。

php で html タグや php タグを削除する便利な関数。

 

strip_tags

公式のマニュアルはこちら、簡単な関数。

 

string strip_tags ( string $str [, string $allowable_tags ] )

パラメータは2つ、1つめは必須で、2つめは許可するタグを指定できるオプションの引数。

 

使ってみる

実際に使って確認。

まずは file_get_contents で http://example.com を表示するだけのサンプル。

<?php
$html = file_get_contents( 'http://example.com/' );
echo $html;
?>

 

http://example.com のソースはこんな。

<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 50px;
        background-color: #fff;
        border-radius: 1em;
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        body {
            background-color: #fff;
        }
        div {
            width: auto;
            margin: 0 auto;
            border-radius: 0;
            padding: 1em;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.</p>
    <p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

 

これを実行すると、http://example.com のソースを引っ張ってくるのでそのまま表示される。

example.com が表示される
example.com と同じのがそのまま表示される

 

strip_tags してみる

まずは1つめの引数だけ使って。

<?php
$html = file_get_contents( 'http://example.com/' );
echo strip_tags( $html );
?>

 

これで全てのタグが除去されて、こうなる。

strip_tags によりタグというタグが取り除かれる
strip_tags によりタグというタグが取り除かれる

 

インラインスタイルの <style></style> 内は残る。

 

2つめの引数で除外してみる

<style> タグを指定。

<?php
$html = file_get_contents( 'http://example.com/' );
echo strip_tags( $html, '<style>' );
?>

 

ちゃんと <style> だけ残った。

除外できた。複数指定も可。
除外できた。複数指定も可。

 

注意点

ドキュメントに書いてあるとおり、

strip_tags() は HTML の検証を行わないため、 不完全または壊れたタグにより予想以上に多くのテキスト/データが削除される可能性があります。

乱れた HTML だと実行結果が芳しくないかもしれないので注意。

おわり。


投稿日

カテゴリー:

投稿者:

タグ:

コメント

コメント、してみません?

%d人のブロガーが「いいね」をつけました。