繁体   English   中英

如何在 PHP 中替换字符串中一个数字加上带逗号的空格的所有匹配项

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM