addslashes和addcslahes

时间:2010-05-08 23:09:27

标签: php

我今天看到了php.net中的addslashes和addcslashes,但没有说明它们之间的区别是什么是这两个中逃脱的字符。

<?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
?>

如果我对$ decoding变量和echo $ encoded进行注释,我会得到原始字符串中的相同值。

任何人都可以清楚地向我解释这两者的区别和用法。

2 个答案:

答案 0 :(得分:16)

addslashes只能逃脱

  

单引号('),双引号(“),反斜杠()和NUL

您可以使用addcslashes来转义任意字符集。

echo addcslashes("where's the party?", "party");

yeilds

  

是什么\ \ \ \ \ \ \ \ r \ t \ y?

当您需要创建任意控制字​​符或准备以任意格式传输/使用的数据时,这非常有用。例如,如果要在将用户输入作为正则表达式的一部分使用之前要转义用户输入,则可以执行以下操作

preg_match('/match something here plus' . addcslashes($userInput, ".\\+*?[^]($)") . '/', $foo);

但是,这相当于quotemeta,但这只是一个例子。


更多解释

对于刚接触该方法的人来说有时会让人感到困惑,并且我认为对于第二个参数的其余PHP库所提出的事实是一个字符串列表,因为这不会出现在其他任何地方图书馆(据我所知)。

如果第二个参数是一个数组,对某些人来说更有意义,并且更符合要求。

echo addcslashes("where's the party?", array("p", "a", "r", "t", "y"));

这可能有助于某些人以这种方式将其可视化,然后可以将其转换为以下内容:

echo addcslashes(
    "where's the party?", 
    implode("", array("p", "a", "r", "t", "y"))
);

答案 1 :(得分:1)

addcslashes用于转义您传递的字符作为第二个参数。

如果您尝试阅读the docs of stripcslashes,您会发现“识别C-like \ n,\ r \ n ...,八进制和十六进制表示。”