e__
e__

Reputation: 402

Add comma after every word (except final word)

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

Answers (6)

Randhir Kumar
Randhir Kumar

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

Real Sauravarya
Real Sauravarya

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

pp19dd
pp19dd

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

WWW
WWW

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

Brad
Brad

Reputation: 163438

implode(', ', explode(' ', $base_string));

Upvotes: 4

Bojangles
Bojangles

Reputation: 101513

Give rtrim() a go:

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

This will strip any comma from the end of your string. I've wrapped str_replace() in the rtrim() function to keep it on one line, but it might be clearer to split it into two.

Upvotes: 2

Related Questions