simple trim would be enough:
$string = trim($string, " ,");
Note that the second parameter of trim() function allows you to trim defined characters from your string, not just the whitespace. Therefore there are two chars defined in my usage: The space character " " and the comma ",".
and if you look for capitalizing the words without a loop:
$string = ucwords(trim($string, " ,"));
Note: as ucwords() function looks for whitespace to define word boundaries, "apple,apple" won't work but "apple, apple" would work, so:
$string = ucwords(str_replace(array(","," "),array(", "," "),trim($string, " ,")));
is the best solution. (There are two spaces in the second element of first replacement array.)