문제

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);
도움이 되었습니까?

해결책

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

Something like:

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top