簡體   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