Perhaps the following is a more efficient JavaScript escape function:
<?php
function jsEscape($str) {
return addcslashes($str,"\\\'\"&\n\r<>");
}
?>
addcslashes
(PHP 4, PHP 5)
addcslashes — C 言語と同様にスラッシュで文字列をクォートする
説明
charlist パラメータに羅列された文字の前にバックスラッシュを付けた文字列を返します。
パラメータ
- str
-
エスケープしたい文字列。
- charlist
-
エスケープの対象となる文字を並べたもの。 charlist が \n, \r 等の文字を含んでいる場合、 C言語と同様の手法によりエスケープされます。 アスキーコードが32未満または126より大きい文字は、8進表現に変換されます。
charlist 引数の文字の列びを定義する際には、 範囲の最初と最後で指定する文字集合に含まれる文字の種類を把握するようにしてください。
また、ある範囲を指定する最初の文字がその範囲の2番目の文字よりも大きな ASCII 値を有している場合、範囲は定義されません。 最初と最後の文字とピリオド文字のみがエスケープされます。 ある文字の ASCII 値を見つけるには、 ord() 関数を使用してください。<?php
echo addcslashes('foo[ ]', 'A..z');
// 出力: \f\o\o\[ \]
// 全ての大文字と小文字はエスケープされます。
// ... しかし、[\]^_` もエスケープされてしまいます。
?><?php
echo addcslashes("zoo['.']", 'z..A');
// 出力: \zoo['\.']
?>エスケープ文字を0, a, b, f, n, r, t , vとする場合には注意してください。 これらは、\0, \a, \b, \f, \n, \r, \t , \v に変換されます。PHPでは、 \0 (NULL), \r (復改文字), \n (改行文字), \f (フォームフィード), \v (垂直タブ), \t (タブ) が定義済みのエスケープシーケンスですが、C言語では、 これら全てが定義済みのエスケープシーケンスです。
返り値
エスケープされた文字列を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 5.2.5 | エスケープシーケンス \v と \f が追加されました。 |
例
"\0..\37" のように charlist に範囲を指定可能です。この場合、アスキーコードが 0 から 31 の範囲の文字は全てエスケープされます。
例1 addcslashes() の例
<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>
参考
- stripcslashes() - addcslashes でクォートされた文字列をアンクォートする
- stripslashes() - クォートされた文字列のクォート部分を取り除く
- addslashes() - 文字列をスラッシュでクォートする
- htmlspecialchars() - 特殊文字を HTML エンティティに変換する
- quotemeta() - メタ文字をクォートする
addcslashes() treats NUL as a string terminator:
assert("any" === addcslashes("any\0body", "-"));
unless you order it backslashified:
assert("any\\000body" === addcslashes("any\0body", "\0"));
(Uncertain whether this should be declared a bug or simply that addcslashes() is not binary-safe, whatever that means.)
Be carefull with adding the \ to the list of encoded characters. When you add it at the last position it encodes all encoding slashes. I got a lot of \\\ by this mistake.
So always encode \ at first.
Forgot to add something:
The only time you would likely use addcslashes() without specifying the backslash (\) character in charlist is when you are VALIDATING (not encoding!) a data string.
(Validation ensures that all control characters and other unsafe characters are correctly encoded / escaped, but does not alter any pre-existing escape sequences.)
You can validate a data string multiple times without fear of "double encoding". A single decoding pass will return the original data, regardless of how many times it was validated.)
If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist!
Example:
<?php
$originaltext = 'This text does NOT contain \\n a new-line!';
$encoded = addcslashes($originaltext, '\\');
$decoded = stripcslashes($encoded);
//$decoded now contains a copy of $originaltext with perfect integrity
echo $decoded; //Display the sentence with it's literal \n intact
?>
If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction.
jsAddSlashes for XHTML documents:
<?php
header("Content-type: text/xml");
print <<<EOF
<?xml version="1.0"?>
<html>
<head>
<script type="text/javascript">
EOF;
function jsAddSlashes($str) {
$pattern = array(
"/\\\\/" , "/\n/" , "/\r/" , "/\"/" ,
"/\'/" , "/&/" , "/</" , "/>/"
);
$replace = array(
"\\\\\\\\", "\\n" , "\\r" , "\\\"" ,
"\\'" , "\\x26" , "\\x3C" , "\\x3E"
);
return preg_replace($pattern, $replace, $str);
}
$message = jsAddSlashes("\"<Hello>\",\r\n'&World'\\!");
print <<<EOF
alert("$message");
</script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
EOF;
?>
<?php
function jsaddslashes($s)
{
$o="";
$l=strlen($s);
for($i=0;$i<$l;$i++)
{
$c=$s[$i];
switch($c)
{
case '<': $o.='\\x3C'; break;
case '>': $o.='\\x3E'; break;
case '\'': $o.='\\\''; break;
case '\\': $o.='\\\\'; break;
case '"': $o.='\\"'; break;
case "\n": $o.='\\n'; break;
case "\r": $o.='\\r'; break;
default:
$o.=$c;
}
}
return $o;
}
?>
<script language="javascript">
document.write("<? echo jsaddslashes('<h1 style="color:red">hello</h1>'); ?>");
</script>
output :
<script language="javascript">
document.write("\x3Ch1 style=\"color:red\"\x3Ehello\x3C/h1\x3E");
</script>
I have found the following to be much more appropriate code example:
<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\@\177..\377");
?>
This will protect original, innocent backslashes from stripcslashes.
