Reputation: 402
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 ,
Upvotes: 5
Views: 19728
Reputation: 1
In PHP
Let a array as,
$lists=Array ( [0] => 12 [1] => 9 [2] => 10 [3] => 8 )
and we want it to print as 12,9,10,8
Simply using implode
,
Syntax:
implode(glue, pieces)
$items=implode( $lists, ",");
Upvotes: 0
Reputation: 1
Add comma in string without any function....its simple nd 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;
Upvotes: 0
Reputation: 3633
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 );
Should get you what you want: "French, History, Maths, Physics, Spanish, Chemistry"
Upvotes: 3
Reputation: 9860
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.
Upvotes: 4