Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Add Comma after every Word (Except Final)

Tags:

php

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 ,
like image 377
e__ Avatar asked Mar 23 '12 17:03

e__


2 Answers

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.

like image 101
WWW Avatar answered Oct 04 '22 13:10

WWW


implode(', ', explode(' ', $base_string));
like image 24
Brad Avatar answered Oct 04 '22 14:10

Brad