文字列を置換するpreg_replace()関数を使って文字をエスケープする汎用関数(重要)

引数で与えられた文字列で次の置換を行って結果を返す汎用関数

& -> &
< -> &lt;
> -> &gt;
" -> &quot;


これは見出し2です


<h2 style="color:red;">これは見出し2です</h2>
source

<?php
function myEscape($text)	{
	$t = $text;
	$t = str_replace("&","&amp;",$t);
	$t = str_replace("<","&lt;",$t);
	$t = str_replace(">","&gt;",$t);
	$t = str_replace('"','&quot;',$t);
	return $t;
}

$tmp = '<h2 style="color:red;">これは見出し2です</h2>';
echo $tmp."<br>\n";
echo myEscape($tmp);
?>