![](/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.