PHP: add a comma after each word (except for the ending)

I have a string (not an array, this is loading words stored on one line), and I would like to put a comma after each word, although not put it after the last word. I have:

echo str_replace(' ', ', ', $stilltodo); 

but for some reason adds a space before the comma (and after too, but that's right), and also one at the end. How can I change it to work as I want.

Example string "base"

 French History Maths Physics Spanish Chemistry Biology English DT Maths History DT Spanish English French RS 

Current output example with code above

 French , History , Maths , Physics , Spanish , Chemistry , Biology , English , DT , Maths , History , DT , Spanish , English , French , RS , 
+4
source share
5 answers

Try the following:

 $newstring = implode(", ", preg_split("/[\s]+/", $oldstring)); 

preg_split() will split your string into an array and implode() collapse everything together into one string. The regular expression used in preg_split() will take care of any cases where you may have multiple spaces between words.

+5
source
 implode(', ', explode(' ', $base_string)); 
+3
source

Use implode / explode.

 $t = "French History Maths Physics Spanish Chemistry"; // turn this into an array $a = explode(" ", $t ); // output without final comma echo implode(", ", $a ); 

You should get what you want: "French, history, mathematics, physics, Spanish, chemistry"

+2
source

Give rtrim() a go:

 echo rtrim(str_replace(' ', ', ', $stilltodo, ','); 

This will remove any comma from the end of your line. I wrapped str_replace() in the rtrim() function to save it on one line, but it might be clearer to split it into two parts.

+1
source

Add comma to string without any function .... its simple nd is 100% working

 <?php $arr = array(1,2,3,4,6,8,8,8,9); $str = ''; foreach ($arr as $key => $value) { $str = ($str == '' ? '' : $str . ',') . $value; } echo $str; 
0
source

Source: https://habr.com/ru/post/1403134/


All Articles