regexp add space after period but not when period

2019-07-20 17:08发布

问题:

Using php regexp in a simple way, is it possible to modify a string to add a space after periods that follow words but not after a period that is preceded and followed by a number such as 1.00? I also need it to ignore single letter abbreviations such as N.Y.

String.Looks like this.With an amount of 1.00 and references N.Y.

Needs to be changed to...

String. Looks like this. With an amount of 1.00 and references N.Y.

This should allow for multiple instances within the string of course...

回答1:

$text = preg_replace('/(\.)([[:alpha:]]{2,})/', '$1 $2', $text);


回答2:

You can use this regex:

/((?<=[A-Za-z0-9])\.(?=[A-Za-z]{2})|(?<=[A-Za-z]{2})\.(?=[A-Za-z0-9]))/

And the replacement string is '. '.

Note that the regex above expects at least one alphabetical character on one side of the full stop ., and expects alphanumeric character on the other side.

Test string:

"String.Looks like this.With an amount of 1.00 and references N.Y.Mr.NoOne.30% replaced.no 50.Don't know."

Output:

"String. Looks like this. With an amount of 1.00 and references N.Y. Mr. NoOne. 30% replaced. no 50. Don't know."