Page 1 of 1

Help triming a string

Posted: Sun Jul 20, 2003 7:09 pm
by farfromrest
I need to figure out some way to trim of the last , in a string.

Posted: Sun Jul 20, 2003 7:17 pm
by __autoload()

Code: Select all

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

//$string = 'Space';
?>
I'm not sure what you want...

Posted: Sun Jul 20, 2003 7:18 pm
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

Posted: Mon Jul 21, 2003 3:25 am
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...

Posted: Mon Jul 21, 2003 7:16 am
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.