I've got a string (not an array, it's a load of words stored in one string) and I'd like to put a comma after every word, although not putting one after the last word. I've got;
echo str_replace(' ', ', ', $stilltodo);
but that for some reason adds a space before the comma (and after too but that's right), and also one at the end too. How could I change it to work how I want.
An Example of the 'base' String
French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS
An Example of the Current Output with the Code above
French , History , Maths , Physics , Spanish , Chemistry , Biology , English , DT , Maths , History , DT , Spanish , English , French , RS ,
Try this:
$newstring = implode(", ", preg_split("/[\s]+/", $oldstring));
The preg_split()
will split up your string into an array and the implode()
will collapse it all back together into a single string. The regex used in the preg_split()
will take care of any instances you might have multiple spaces between words.
implode(', ', explode(' ', $base_string));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With