-->

2013-07-27

htmlタグをエスケープするコマンド

$ cat html3.txt
<html>
 <head>
  <title>"test"</title>
 </head>
</html>

$ cat html3.txt | perl -pe 's/([<>&])/{"<","&lt;",">","&gt;","&","&amp;"}->{$1}/ge'
&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;"test"&lt;/title&gt;
 &lt;/head&gt;
&lt;/html&gt;

$ cat html3.txt | php -r 'print htmlspecialchars(file_get_contents("php://stdin"));'
&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;&quot;test&quot;&lt;/title&gt;
 &lt;/head&gt;
&lt;/html&gt;

コマンドのショートカット。
$ which htmlescape
which: no htmlescape in (/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/opt/bin:/usr/x86_64-pc-linux-gnu/gcc-bin/4.6.3:/usr/x86_64-pc-linux-gnu/powerpc-unknown-linux-gnu/gcc-bin/4.5.4)

$ unalias htmlescape
bash: unalias: htmlescape: 見つかりません

$ htmlescape(){ php -r 'print htmlspecialchars(file_get_contents("php://stdin"));'; }

$ cat html3.txt | htmlescape
&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;&quot;test&quot;&lt;/title&gt;
 &lt;/head&gt;
&lt;/html&gt;

http://d.hatena.ne.jp/tanakaBox/20070729/1185709167
http://d.hatena.ne.jp/n9d/20090106/1231237069
http://php.net/manual/ja/function.htmlspecialchars.php
htmlescape(){ read -rd '' s; echo "$s" | perl -pe 's/([<>&\"'\''])/{"<","&lt;",">","&gt;","&","&amp;","\"","&quot;","'\''","&#039;"}->{$1}/ge';}

0 件のコメント: