1
$str = "Hello 1234567 Stack 56789 Overflow 12345";

$str = preg_replace('/([0-9] )/', ',', $str);

I want this "Hello 1234567, Stack 56789, Overflow 12345,..."

1

2 Answers 2

1

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
0
0

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.