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 стил, докато другите не буквено-цифрови знаци с ASCII кодове по-малки от 32 и по-големи от 126 ще бъдат преобразувани до осмично представяне.
Когато дефинирате последователност от знаци в параметъра charlist, уверете се, че знаете кои знаци влизат в обхвата между началния и крайния знак.
<?php
echo addcslashes('foo[ ]', 'A..z');
// изход: \f\o\o\[ \]
// Всички знаци в горен и долен регистър ще бъдат екранирани
// ... също така [\]^_`
?>Също така, ако първият знак от обхвата има по-голяма ASCII стойност от последния знак - обхват няма да бъде създаден. Само началният, крайният и знакът "точка" ще бъдат екранирани. Можете да използвате функцията ord(), за да намерите ASCII стойността на даден знак.
<?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. |
Примери
При стойност на параметъра charlist - "\0..\37", ще бъдат екранирани всички знаци с ASCII код между 0 и 31.
Example #1 Пример за addcslashes()
<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>
Вж. също
- stripcslashes() - Премахва екранирането на знаците, екранирани с функцията addcslashes
- stripslashes() - Премахва екранирането на екраниран низ
- addslashes() - Екранира специалните знаци в низ
- htmlspecialchars() - Преобразува специални знаци в HTML единици
- quotemeta() - Екранира специалните знаци
<?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>
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.
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.
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.)
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;
?>
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.
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.)
