Help triming a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
farfromrest
Forum Newbie
Posts: 11
Joined: Sun Jul 20, 2003 7:09 pm

Help triming a string

Post by farfromrest »

I need to figure out some way to trim of the last , in a string.
__autoload()
Forum Newbie
Posts: 7
Joined: Tue Jul 15, 2003 10:43 am

Post by __autoload() »

Code: Select all

<?php
$string = 'Space                         ';
$string = rtrim($string);

//$string = 'Space';
?>
I'm not sure what you want...
Last edited by __autoload() on Mon Jul 21, 2003 3:19 am, edited 1 time in total.
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

To remove the last , use substr();

Code: Select all

<?php
$text = "one, two, three,";
$text = substr($text, 0, -1);

echo($text);
?>
That should work.. 8O
__autoload()
Forum Newbie
Posts: 7
Joined: Tue Jul 15, 2003 10:43 am

Post by __autoload() »

Oh, you mean remove the last comma..
Gen-ik, that code you gave wouldn't work if the string was :

Code: Select all

<?php
$string = 'one , two ,three';
?>
It'd only remove the last character. I think you'd have to use pattern matching for this...
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Good point. Ok.. so let's check to see if the last character is a , before we attempt to chop it off....

Code: Select all

<?php
$text = "one, two, three,"; 

if(substr(trim($text), 0, -1)==",")
{
$text = substr(trim($text), 0, -1);
}

echo($text); 
?>

By the way the trim() command simply chops off any 'white space' from the begining and ends of a variable... not always needed but it keeps your text tidy.
Post Reply