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?

Was it helpful?

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

OTHER TIPS

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.

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