Andy Groom
Andy Groom

Reputation: 629

Trim specific character from beginning and end of string

I just wondered if there was a more efficient way of removing a comma (if there is one) from the beginning and end of a string?

if (substr($_SESSION['login_dashboard'], 0, 1)==",") $_SESSION['login_dashboard'] = substr($_SESSION['login_dashboard'], 1);
if (substr($_SESSION['login_dashboard'], -1, 1)==",") $_SESSION['login_dashboard'] = substr($_SESSION['login_dashboard'], 0, -1);

Upvotes: 1

Views: 12791

Answers (3)

Waqas Shahid
Waqas Shahid

Reputation: 1060

Yes you can use trim() function:

echo trim($_SESSION['login_dashboard'],',');

Upvotes: 2

Kausha Mehta
Kausha Mehta

Reputation: 2928

You could use trim():

$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');

Upvotes: 3

Bikash
Bikash

Reputation: 1938

$char = ",test,test2,test3,";
echo trim($char,',');

output is

test,test2,test3

Upvotes: 2

Related Questions