Question

I have lots of input sentences I want to normalize. What they have in common is that they don't have spaces after commas and periods.

Oval,delicate cupcakes.Very tasty.Enjoy.

What is a quickest way to normalize such sentences?

Était-ce utile?

La solution

You can use:

$sentence = preg_replace('/([,.])(?!\s)/', '$1 ', $sentence);
  • [.,] - match either a dot or comma
  • ([.,]) - match and group for backreference
  • (?!\s) is negative lookahead which means match if not followed by a space

Autres conseils

Try this regex:

$string = preg_replace("/([,.])(?!\s|$)/", "$1 ", $string);

Using negative lookahead (?!\s|$) it is checking whether the , or . is not before a space or end of line.

If you want to get more detail explanation of the regex, just use this link.

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