[SOLVED] Removing spaces from the start and end of 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
starsol
Forum Newbie
Posts: 24
Joined: Thu Jul 31, 2003 8:30 am
Location: Norfolk, England.
Contact:

Removing spaces from the start and end of a string

Post by starsol »

I'm having a few problems trying to remove spaces from the beginning and end of a sting (if either or both first and last character is a space). Any spaces in the middle of the string are ok, so str_replace isn't the solution.

What I have so far is:

Code: Select all

$length = strlen($string);
$explode = explode("", $string);
if ($explodeї0] == " "){
	array_shift($explode);
}
if ($explodeї$length]) == " "){
	array_pop($explode);
}
$string = implode("", $explode);
This of course gives parse errors at $explode[length]. Can anyone advise me how I can check if the last value in the exploded array is a space?
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

php-manual: ltrim() and rtrim()
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

also [php_man]trim[/php_man]() will remove leading and trailing spaces at the same time.
starsol
Forum Newbie
Posts: 24
Joined: Thu Jul 31, 2003 8:30 am
Location: Norfolk, England.
Contact:

Post by starsol »

Cheers B).
Post Reply