Andres SK
Andres SK

Reputation: 10974

Automatically adding spaces after periods and commas, while avoiding numbers

This is the current regex I use to sanitize sentences when people write something like:

Hello.I'm Andres,right?

It will be automatically converted to:

Hello. I'm Andres, right?

The problem comes up when there are numbers inside the string. Example:

I have 40.381,32 dollars.

...will be converted to:

I have 40. 381, 32 dollars.

My current code:

echo preg_replace( '/[!?,.](?![!?,.\s])/', '$0 ', 'Hello my friend.There should be a space after sentence periods and commas, but that should not apply to 40.381,32 numbers.');

Question: how can I avoid these rules to be applied when the ,. characters are between numbers? Thanks!

Upvotes: 3

Views: 2064

Answers (1)

Ωmega
Ωmega

Reputation: 43683

Use regex pattern

(?<!\d)[.,!?](?!\d)

or

(?<!\d)[.,!?](?![.,!?\d])

Upvotes: 4

Related Questions