関数htmlspecialchars

関数 htmlspecialchars は、ブラウザがタグをコマンドとしてではなく文字列として表示するようにするものです。この関数は、アンパサンド & を &amp; に、山括弧 < を &lt; に、山括弧 > を &gt; に変換します。

可能なすべてのHTMLエンティティを変換する必要がある場合は、htmlentities を使用してください。

構文

phphtmlspecialchars(string $string, int $flags = ENT_COMPAT, ?string $encoding = null, bool $double_encode = true): string

例

タグを含む文字列を変換してみましょう:

php<?php
  echo htmlspecialchars('<b>bold text</b>');
?>

コードの実行結果:

php'<b>text</b>'

例

アンパサンドを含む文字列を変換してみましょう:

php<?php
  $str = 'test: &';
  $res = htmlspecialchars($str);
  
  echo $res;
?>

コードの実行結果:

php'test: &'

関連項目