gpt4 book ai didi

php - addslashes 和 addcslahes

转载 作者:可可西里 更新时间:2023-11-01 13:36:45 25 4
gpt4 key购买 nike

我今天在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com