gpt4 book ai didi

php - 解释单引号字符串中的转义字符

转载 作者:可可西里 更新时间:2023-10-31 22:47:36 26 4
gpt4 key购买 nike

有一个单引号字符串:

$content = '\tThis variable is not set by me.\nCannot do anything about it.\n';

我想解释/处理字符串,就好像它是双引号。换句话说,我想替换 all 可能的 escape characters (不仅仅是本例中的制表符和换行符)与实际值,考虑到反斜杠也可能被转义,因此“\\n”需要替换为“\n”。 eval() 可以轻松完成我需要的操作,但我无法使用它。

是否有一些简单的解决方案?

(我发现一个 similar thread 在替换转义字符后处理单引号字符串中的变量扩展。)

最佳答案

有一个非常简单的方法可以做到这一点,基于 preg_replaceDocstripcslashes ,它们都内置于:

preg_replace_callback(
'/\\\\([nrtvf\\\\$"]|[0-7]{1,3}|\x[0-9A-Fa-f]{1,2})/',
fn($matches) => stripcslashes($matches[0]), $content
);

只要 "\\n" 应该变成 "\n" 之类的,它就可以工作。 Demo

如果您要逐字处理这些字符串,请参阅我的 previous answer

编辑:您在评论中提问:

I'm just a bit puzzled what's the difference between the output of this and stripcslashes() directly [?]

差异并不总是可见,但有一个:如果后面没有转义序列,stripcslashes 将删除 \ 字符。在 PHP 字符串中,在这种情况下不会删除斜杠。例如,"\d"d 不是特殊字符,因此 PHP 保留了斜杠:

$content = '\d';
$content; # \d
stripcslashes($content); # d
preg_replace(..., $content); # \d

这就是为什么 preg_replace 在这里很有用,它只会将函数应用于那些 stripcslashes 按预期工作的子字符串:所有有效的转义序列。


几年后,答案更新为 PHP 7.4+。

原始答案确实包含一个在正则表达式中使用 e (eval) 修饰符的 Demo。由于(主要是好的)原因,它已从 PHP 中删除并拒绝工作,并出现如下错误:

PHP Warning: preg_replace(): The /e modifier is no longer supported, use preg_replace_callback

如果新版本出现语法错误(例如 PHP < 7.4)或出于偏好,请将箭头函数替换为匿名函数,例如:

static function (array $matches): string {
return stripcslashes($matches[0]);
}

请参阅 Replace preg_replace() e modifier with preg_replace_callback 以获取更多关于替换 e 修饰符的主题的现场问答资源,它在 PHP 5.5.0 中已被弃用:

[The] e (PREG_REPLACE_EVAL) [...] was DEPRECATED in PHP 5.5.0 (Jun 2013), and REMOVED as of PHP 7.0.0 (Dec 2015).

from the PHP manual

关于php - 解释单引号字符串中的转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309731/

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