addcslashes

(PHP 4, PHP 5, PHP 7)

addcslashesC 형식으로 문자열을 슬래시로 인용

설명

string addcslashes ( string $str , string $charlist )

charlist 인수에 주어진 문자 목록 앞에 백슬래시를 추가한 문자열을 반환합니다.

인수

str

이스케이프할 문자열.

charlist

이스케이프할 문자 목록. charlist\n, \r 등을 가지면 C 형식으로 변환되고, 아스키 코드로 32 미만 126 초과 문자들은 8진 표현으로 변환합니다.

charlist 인수에 문자 시퀀스를 정의할 때, 처음에서 끝 범위에 어떠한 문자가 들어가는지 확인하십시오.

<?php
echo addcslashes('foo[ ]''A..z');
// 출력:  \f\o\o\[ \]
// 모든 대소문자를 이스케이프합니다.
// ... 하지만 [\]^_` 도 포함됩니다.
?>
또한, 범위 지정에서 처음 문자가 나중 문자보다 큰 아스키 값을 가지면 범위를 형성하지 않습니다. 단지 처음과 마지막, 피리오드(.)문자만을 이스케이프합니다. 문자의 아스키 값을 찾아보려면 ord() 함수를 이용하십시오.
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"처럼 넣으면, 아스키 코드 0에서 31까지의 모든 문자를 이스케이프합니다.

Example #1 addcslashes() 예제

<?php
$escaped 
addcslashes($not_escaped"\0..\37!@\177..\377");
?>

참고

add a note add a note

User Contributed Notes 8 notes

up
5
phpcoder at cyberpimp dot pimpdomain dot com
19 years ago
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.
up
4
stein at visibone dot com
16 years ago
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.)
up
3
natNOSPAM at noworrie dot NO_SPAM dot com
21 years ago
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.
up
2
glitchmr at myopera dot com
10 years ago
If you need JS escaping function, use json_encode() instead.
up
-2
Johannes
16 years ago
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.
up
-2
vishal dot ceeng at gmail dot com
4 years ago
echo addcslashes("zoo['.']", 'z..A');

Above code will create an error as per below

Invalid '..'-range, '..'-range needs to be incrementing -
up
-21
ruben at intesys dot it
19 years ago
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;
?>
up
-25
Anonymous
20 years ago
<?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>
To Top