Question

I'm currently using

$text= preg_replace('/(?<=[a-zA-Z])[.](?![\s$])/','. ',$text);

To edit sentences in PHP but I have a problem here is an example:

This is my example text. After this sentence there is no space after dot.Some other sentence.

What should I do? I want PHP to add white space in that case, but not after sentence that already have white space or that is ended by "..."

Another unwanted behavior is with numbers. For example :

How great is it to win 1.000.000 on the lottery!

I really don't want it to become 1. 000. 000 after edititng.

Also same thing with C.J.. It must stay C.J. and not C. J.

So in short there should be white spaces when :

  • "." NOT followed by number (can be other sign)
  • ignore when there are more than one dot like "..."
  • ignore when there is 1 or 2 letter words before the dot.
Was it helpful?

Solution

$text = preg_replace('/(?<! [a-z]| [a-z]{2})\.(?! |\d|\.)/i', '. ', $text);

See it here in action: http://regex101.com/r/zE4pI4


This can get even more complicated if you want to take into account initials at the beginning of your text (see here how it fails). Since the lookbehind has to be fixed length, you'll have to create a separate lookbehind for that:

/(?<! [a-z]| [a-z]{2})(?<!\b[a-z]|\b[a-z]{2})\.(?! |\d|\.)/

See it here in action: http://regex101.com/r/pH1mZ5

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top