m3tsys
m3tsys

Reputation: 3969

How to delete last comma from comma separated words string in php?

Let's say my string like:

$string = 'lorem, ipsum, dolor, sit, amet, ';

or $string = 'lorem, ipsum, dolor, sit, amet,';

How to transform that to something like this?

$string = 'lorem, ipsum, dolor, sit, amet';

// the string is generated by this code:

$count = count($taglist);
for ($i = 0; $i < $count; $i++) {
$videoData['tags'] .= $taglist[$i].', ';
}

Upvotes: 1

Views: 2831

Answers (7)

user1288802
user1288802

Reputation: 83

A less PHP specific soultion that is a convention, and good habit to get into is this...

var modString = "";
for(var i = 0; i < LIMIT_NUM; i++) {
    if(modString.length() > 0) modString += ",";
    modString += "content";
}

This is simalary to javascript code but the idea is simple...check if the string has anything in it and if it does add the comma BEFORE the content.This will work in any language and is the way i see it done most often. You need conventions for this sort of thing vs. calling a library for something so simple.

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

trim($string, " ,");

Removes trailing commas (plus the default spaces, newlines etc) from both start and end of the string.

Upvotes: 3

Alex Howansky
Alex Howansky

Reputation: 53563

I'm guessing this string is being built programmatically elsewhere via a loop like this:

$str = '';
some loop {
    $str .= $item . ', ';
}

And you're left over with an extra ", " at the end of the loop. If this is the case, I'd recommend doing this instead:

$list = array();
some loop {
    $list[] = $item;
}
$str = implode(', ', $list);

Upvotes: 4

Computer_Engineer
Computer_Engineer

Reputation: 403

You can use substr(trim($string),0,-1) to remove last char and whitespaces.

Upvotes: 0

j08691
j08691

Reputation: 207901

$string = substr(trim($string),0,-1);

Upvotes: 2

Yoshi
Yoshi

Reputation: 54649

$string = rtrim($string, ', ');

Upvotes: 6

LeeR
LeeR

Reputation: 1636

Try this....

$string = rtrim($string, ', ');

Upvotes: 0

Related Questions