Search code examples
phpregexpunctuation

regexp add space after comma but not when comma is thousands separator?


Using php regexp in a simple way, is it possible to modify a string to add a space after commas and periods that follow words but not after a comma or period that is preceded and followed by a number such as 1,000.00?

String,looks like this with an amount of 1,000.00

Needs to be changed to...

String, looks like this with an amount of 1,000.00

This should allow for multiple instances of course... Here is what I am using now but it is causing numbers to return as 1, 000. 00

$punctuation = ',.;:';
$string = preg_replace('/(['.$punctuation.'])[\s]*/', '\1 ', $string);

Solution

  • You could replace '/(?<!\d),|,(?!\d{3})/' with ', '.

    Something like:

    $str = preg_replace('/(?<!\d),|,(?!\d{3})/', ', ', $str);