I have a php variable that comes from a form that needs tidying up. I hope you can help.
The variable contains a list of items (possibly two or three word items with a space in between words).
I want to convert it to a comma separated list with no superfluous white space. I want the divisions to fall only at commas, semi-colons or new-lines. Blank cannot be an item.
Here’s a comprehensive example (with a deliberately messy input):
Variable In: "dog, cat ,car,tea pot,, ,,, ;;(++NEW LINE++)fly, cake"
Variable Out "dog,cat,car,tea pot,fly,cake"
Can anyone help?
You can start by splitting the string into “useful” parts, with
preg_split, and, then,implodethose parts back together :(Here, the regex will split on ‘
,‘, ‘;‘, and ‘\s‘, which means any whitespace character — and we only keep non-empty parts)Will get you, for
$parts:And, for
$str_out:Edit after the comment : sorry, I didn’t notice that one ^^
In that case, you can’t split by white-space 🙁 I would probably split by ‘
,‘ or ‘;‘, iterate over the parts, usingtrimto remove white-characters at the beginning and end of each item, and only keep those that are not empty :Executing this portion of code gets me :
And imploding all together, I get, this time :
Which is better 😉