You can either use php methods:
// $str <- "This is a long string";
$comma_str = implode(',', explode(' ',$str));
or
$comma_str = str_replace(' ', ',', $str);
Or use a regexp.
2
solved How to split a sentence into separate words followed by a comma using PHP [closed]