![](/img/trans.png)
[英]How to use PHP regex to replace a space AND comma AND combination of space AND comma with arbitrary string?
[英]How to replace in PHP all matches of a digit plus a space with comma in a string
$str = "Hello 1234567 Stack 56789 Overflow 12345";
$str = preg_replace('/([0-9] )/', ',', $str);
我想要这个“你好 1234567,堆栈 56789,溢出 12345,......”
利用
preg_replace('/\d(?=\s)/', '$0,', $str)
见证明。
表达式解释
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
) end of look-ahead
我会使用正则表达式逻辑,它明确地针对左边有数字和右边有字母的空格:
$input = "Hello 1234567 Stack 56789 Overflow 12345";
$output = preg_replace('/(?<=\d) (?=\D)/', ', ', $input);
echo $input . "\n" . $output;
这打印:
Hello 1234567 Stack 56789 Overflow 12345
Hello 1234567, Stack 56789, Overflow 12345
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.