Remove repetitve Consecutive words from string

$after = preg_replace('/(?<=^|,)([^,]+)(,\s*\1)+/', '$1', $str);

P.S. You can get rid of \s* from the regexp above if there is no whitespace expecter after ,. I just looked at your [ ]* and figured you may have whitespace.


You should use

preg_replace('~(?<![^,])([^,]+)(?:,\1)+(?![^,])~', '$1', $str)

See the regex demo

If there is a need to support any 0 or more whitespace chars between the commas and repetitive values, add \s* (0 or more whitespaces) pattern before \1.

Details

  • (?<![^,]) - start of string or any char but a comma
  • ([^,]+) - Group 1: any one or more chars other than a comma
  • (?:,\1)+ - one or more sequences of a comma and the value in Group 1
  • (?![^,]) - end of string or a char other than a comma.