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
Вопрос
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?
Решение
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Другие советы
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.