$str = "Hello 1234567 Stack 56789 Overflow 12345";
$str = preg_replace('/([0-9] )/', ',', $str);
I want this "Hello 1234567, Stack 56789, Overflow 12345,..."
Use
preg_replace('/\d(?=\s)/', '$0,', $str)
See proof.
Expression explanation
--------------------------------------------------------------------------------
\d digits (0-9)
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
) end of look-ahead
I would use regex logic which explicitly targets spaces with numbers to the left and letters to the right:
$input = "Hello 1234567 Stack 56789 Overflow 12345";
$output = preg_replace('/(?<=\d) (?=\D)/', ', ', $input);
echo $input . "\n" . $output;
This prints:
Hello 1234567 Stack 56789 Overflow 12345
Hello 1234567, Stack 56789, Overflow 12345