解释单引号字符串中的转义字符 [英] Interpret escape characters in single quoted string
问题描述
使用单引号字符串:
$content = '\tThis variable is not set by me.\nCannot do anything about it.\n';
我想toerpret /处理字符串,就好像是双引号< STRONG>。换句话说,我想将全部替换为 转义字符 (不仅仅是这个例子中的标签和换行符)与实际的值,考虑到反斜杠可能被转义为那么'\\''需要被'\'替换。 eval()将轻松实现我所需要的,但我无法使用它。
I would like to inerpret/process the string as if it was double-quoted. In other words I would like to replace all the possible escape characters (not just tab and linefeed as in this example) with the real values, taking into account that backslash might be escaped as well, thus '\\n' needs to be replaced by '\n'. eval() would easily do what I need but I cannot use it.
是否有一些简单的解决方案?
(A 类似的线程 ,我发现在替换转义字符之后处理单引号字符串中变量的扩展。)
(A similar thread that I found deals with expansion of variables in the single-quoted string while I'm after replacing escape characters.)
推荐答案
根据 preg_replace
Doc 和 stripcslashes
,都建立在:
There is a very simple way to do this, based on preg_replace
Doc and stripcslashes
, both build in:
preg_replace(
'/\\\\([nrtvf\\\\$"]|[0-7]{1,3}|\x[0-9A-Fa-f]{1,2})/e',
'stripcslashes("$0")', $content
);
Th只要\\\\
应该成为\\\
等。 演示。
This works as long as "\\n"
should become "\n"
and the like. Demo.
如果您正在寻找处理这些字符串可以看出我的以前的答案。
If you're looking for processing these strings literally, see my previous answer.
编辑:您在评论中询问:
我只是有点困惑,这个输出有什么区别和stripcslashes()直接[?]
I'm just a bit puzzled what's the difference between the output of this and stripcslashes() directly [?]
差异并不总是可见,但有一个: stripcslashes
将删除 \
chracter,如果没有转义序列。在PHP字符串中,在这种情况下,斜线不会被丢弃。例如,\d
, d
不是一个特殊字符,所以PHP保留斜杠: p>
The difference is not always visible, but there is one: stripcslashes
will remove the \
chracter if no escape sequence follows. In PHP strings, the slash is not be dropped in that case. An example, "\d"
, d
is not a special character, so PHP preserves the slash:
$content = '\d';
$content; # \d
stripcslashes($content); # d
preg_replace(..., $content); # \d
这就是为什么 preg_replace
在这里很有用,它将只适用于 stripcslashes
按照预期工作的那些子串的功能:所有有效的转义序列。
That's why preg_replace
is useful here, it will only apply the function on those substrings where stripcslashes
works as intended: all valid escape sequences.
这篇关于解释单引号字符串中的转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!