在字母数字子字符串和非字母数字子字符串之间插入逗号
我想在字符串中的字母数字(带空格)和非字母数字之间添加逗号。
我尝试过这个:
$str = "This is !@#$%^&";
echo preg_replace("/([a-z0-9_\s])([^a-z0-9_])/i", "$1, $2", $str);
但我得到了这个结果:
This, is, !@#$%^&
如何修复搜索模式以获得这个结果?
This is, !@#$%^&
I want to add a comma between alpha-numeric (with space) and non-alpha-numeric in a string.
I tried with this:
$str = "This is !@#$%^&";
echo preg_replace("/([a-z0-9_\s])([^a-z0-9_])/i", "$1, $2", $str);
But I got this result:
This, is, !@#$%^&
How can I fix the search pattern to get this result?
This is, !@#$%^&
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该为第二组否定第一组中的所有内容,如下所示:
否则,它也会在空格上分裂。
You should have negated everything in the first group for the second, like so:
Otherwise, it'd split on spaces as well.
您可能必须在多次迭代中执行此操作。试试这个:
You will probably have to do this in multiple iterations. Try this:
字符类中字母数字字符的 posix 表达式为
[[:alnum:]]
,但也可以用 case- 写为[az\d]
不敏感的模式修饰符。只需匹配一个或多个 alnum 字符,然后使用
\K
“忘记它们”,然后向前查找后跟非 alnum 字符的空格 ([^[:alnum:]])。这个零宽度匹配将标记应插入逗号的位置。不需要反向引用。
代码:(演示)
The posix expression for alphanumeric characters inside of a character class is
[[:alnum:]]
, but it can also be written as[a-z\d]
with a case-insensitive pattern modifier.Just match one or more alnum character, then "forget them" with
\K
, then lookahead for a space followed by a non-alnum character ([^[:alnum:]]
). This zero-width match will mark the position where a comma should be injected. No backreferences are needed.Code: (Demo)