如何在 PHP 中用字符串中的逗号替换数字加上 space 的所有匹配项
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)/', '[=10=],', $str)
参见proof。
表达式解释
--------------------------------------------------------------------------------
\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
$str = "Hello 1234567 Stack 56789 Overflow 12345";
$str = preg_replace('/([0-9] )/', ',', $str);
我想要这个“你好 1234567,堆栈 56789,溢出 12345,...”
使用
preg_replace('/\d(?=\s)/', '[=10=],', $str)
参见proof。
表达式解释
--------------------------------------------------------------------------------
\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