php - addslashes 和 addcslahes

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

如果我注释 $decoded 变量并回显 $encoded,我得到与原始字符串中相同的值。

谁能给我说清楚这两者的区别和用途

最佳答案

addslashes只逃脱

single quote ('), double quote ("), backslash () and NUL

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

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

产量

whe\re's \the \p\a\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"))
);

关于php - addslashes 和 addcslahes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2795992/

相关文章:

php - Laravel phpunit 模拟键盘按键

php - curl 跨源请求需要用户代理才能工作吗?

php - 将 JSON 数组返回到 Laravel 中的 View

php - 使用 PDO 和 MySQL 更新查询

php - 使用 Laravel 5.0 浏览要上传的文件时如何仅显示 .pdf 文件?

javascript - 网页游戏 - 将 JavaScript 变量保存到 MySQL

php - SSL 错误 : Secure Connection Failed

php - SQL 更新查询在 PHP 中不起作用

javascript - 激活服务器时间上的单选按钮

php - 带有父代码的多列引用