Question

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);
Était-ce utile?

La solution

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

Something like:

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

Autres conseils

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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top