Tyler Mammone
Tyler Mammone

Reputation: 169

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);

Upvotes: 0

Views: 4574

Answers (3)

CARLOS AGUIRRE
CARLOS AGUIRRE

Reputation: 55

Although this is quite old, I was looking for this same question, and after understanding solutions given I have a different answer.

Instead of checking for character before the comma this regex checks the character after the comma and so it can be limited to alphabetic ones. Also this will not create a string with two spaces after a comma.

$punctuation = ',.;:';
$string = preg_replace("/([$punctuation])([a-z])/i",'\1 \2', $string);

Test script can be checked here.

Upvotes: 0

Flo
Flo

Reputation: 1

I was searching for this regex.

This post really help me, and I improve solution proposed by Qtax.

Here is mine:

$ponctuations = array(','=>', ','\.'=>'. ',';'=>'; ',':'=>': ');
foreach($ponctuations as $ponctuation => $replace){
    $string = preg_replace('/(?<!\d)'.$ponctuation.'(?!\s)|'.$ponctuation.'(?!(\d|\s))/', $replace, $string);
}

With this solution, "sentence like: this" will not be changed to "sentence like:  this" (whith 2 blanck spaces)

That's all.

Upvotes: 0

Qtax
Qtax

Reputation: 33918

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

Something like:

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

Upvotes: 1

Related Questions