在字母数字子字符串和非字母数字子字符串之间插入逗号

发布于 2024-08-11 04:59:34 字数 343 浏览 2 评论 0原文

我想在字符串中的字母数字(带空格)和非字母数字之间添加逗号。

我尝试过这个:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦在深巷 2024-08-18 04:59:34

您应该为第二组否定第一组中的所有内容,如下所示:

preg_replace("/([a-z0-9_\s])([^a-z0-9_\s])/i", "$1, $2", $str);

否则,它也会在空格上分裂。

You should have negated everything in the first group for the second, like so:

preg_replace("/([a-z0-9_\s])([^a-z0-9_\s])/i", "$1, $2", $str);

Otherwise, it'd split on spaces as well.

灼疼热情 2024-08-18 04:59:34

您可能必须在多次迭代中执行此操作。试试这个:

$preg = array( "/([\w\s]+)/i", "/([\W\s]+)/i" ):
$replace = array( "\\1, ", "\\1 " );
$result = rtrim( preg_replace( $preg, $replace, $input ) ); // rtrim to get rid of any excess spaces

You will probably have to do this in multiple iterations. Try this:

$preg = array( "/([\w\s]+)/i", "/([\W\s]+)/i" ):
$replace = array( "\\1, ", "\\1 " );
$result = rtrim( preg_replace( $preg, $replace, $input ) ); // rtrim to get rid of any excess spaces
水中月 2024-08-18 04:59:34

字符类中字母数字字符的 posix 表达式为 [[:alnum:]],但也可以用 case- 写为 [az\d]不敏感的模式修饰符。

只需匹配一个或多个 alnum 字符,然后使用 \K“忘记它们”,然后向前查找后跟非 alnum 字符的空格 ([^[:alnum:]])。这个零宽度匹配将标记应插入逗号的位置。不需要反向引用。

代码:(演示

$text = <<<TEXT
This is !@#$%^&
TEXT;

echo preg_replace("/[[:alnum:]]+\K(?= [^[:alnum:]])/", ",", $text);
// This is, !@#$%^&

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)

$text = <<<TEXT
This is !@#$%^&
TEXT;

echo preg_replace("/[[:alnum:]]+\K(?= [^[:alnum:]])/", ",", $text);
// This is, !@#$%^&
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文