[PHP-users 34448] Re: htmlタグのエスケープ処理
itam @ itam.jp
itam @ itam.jp
2009年 3月 19日 (木) 22:02:35 JST
北條(itam)です.こんにちは. % 2009/03/19 21:40:05 JST
個人的にはPHPにはまったく関係ないように思いますが...
とりあえず,気が向いたのでサクッと正規表現にしてみました.
hという要素指定が単なる間違いな気がしますがとりあえず,配列の指定を何
も考えずそのまま置換して定数にしておきました.当然ながら,h1〜h4はもとも
との許可要素に含まれていないので,エスケープされたままですね.
悪しからずご了解ください.
----^ test0003.php ----8<----8<----8<---- BEGIN ----8<----<< cut here
<?php
// 許可要素
define('ALLOW_ELEMENTS', 'br|p|img|font|table|tr|th|td|a|b|big|center|h|hr|strong|tt|u|li|ul');
function escape($sInput){
// まず全てエスケープ
$sEscaped = htmlspecialchars($sInput, ENT_QUOTES);
// 許可要素を元に戻す
$sSearch = '!((<(' . ALLOW_ELEMENTS . ')( .*)?>)|(</(' . ALLOW_ELEMENTS . ')>))!Uie';
$sReplace = 'htmlspecialchars_decode("$1", ENT_QUOTES)';
$sDecoded = preg_replace($sSearch, $sReplace, $sEscaped);
return $sDecoded;
}
// for PHP 4, PHP 5 < 5.1.0
if ( function_exists('htmlspecialchars_decode') === false ) {
function htmlspecialchars_decode($sInput, $iEntType = ENT_COMPAT) {
return strtr($sInput, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $iEntType)));
}
}
$a='<p style="color:red;">赤字</p> <br>
<img src="image.jpg" /><br>
<font color="Green">Green</font><br>
<table border="1">
<tr><th colspan="2">タイトル</th></tr>
<tr><td>左</td><td>右</td></tr>
</table><br>
<a href="eregtest.html" target="_blank_">リンク</a><br>
<b>ボールド</b><br>
<big>ビッグ</big><br>
<center>センタリング</center><br>
<hr>
<h1>H1</h1>
<h2>H2</h2>
<h3>H3</h3>
<h4>H4</h4>
<strong>強調</strong><br>
<tt>TT表示中</tt><br>
<u>アンダーライン</u><br>
<ul>
<li>リスト
<li>リスト
<li>リスト
</ul>
';
var_dump($a);
var_dump(escape($a));
----$ test0003.php ----8<----8<----8<---- END ----8<----<< cut here
--
北條 正樹 itam @ itam.jp http://itam.jp
PHP-users メーリングリストの案内