PHP:转义非字母数字字符
我正在尝试将我不久前在 bash 中编写的脚本移植到 PHP 中。其中一行是关于转义所有非字母数字字符的。
在 bash 中,我能够将其作为一行操作,如下所示:
echo "aaa bbb::" | sed 's/\([^a-zA-Z0-9]\)/\\\1/g'
# => aaa\ bbb\:\:
我在 PHP 中得到的最接近的是这样的:
echo preg_replace('/([^a-zA-Z0-9])/','\\\','aaa bbb::');
# => aaa\bbb\\
但是我正在努力在 preg_replace
中重用我的正则表达式组(我尝试过 \ 1 和 1 美元)。
有人可以帮我正确地写出这段 PHP 语句吗?
I'm trying to port a script that I wrote in bash some time ago into PHP. One particular line is about escaping all non-alphanumeric characters.
In bash, I was able to do it as a one-liner as follows:
echo "aaa bbb::" | sed 's/\([^a-zA-Z0-9]\)/\\\1/g'
# => aaa\ bbb\:\:
The closest I got in PHP was with this:
echo preg_replace('/([^a-zA-Z0-9])/','\\\','aaa bbb::');
# => aaa\bbb\\
However I'm struggling to reuse my regex group inside preg_replace
(I tried \1 and $1).
Can someone help me get this PHP one-liner right please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
[^[:alnum:]]
表示您的语言环境中的所有非字母数字字符,并且不要忘记双倍转义反斜杠:Use
[^[:alnum:]]
to represent all non-alphanumeric characters in your locale and don't forget to double-double escape your backslashes:尝试:
Try: