Search code examples
phpregexpunctuation

Normalize sentence punctuation in php?


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?


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