Jump to content


Photo

*SOLVED* how do you shave empty characters from begin/end of a string


  • Please log in to reply
5 replies to this topic

#1 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 27 July 2006 - 06:44 PM

ok, so i have a string...

$string='foo, bar,blue ,bear,bla bla';

i want each element (separated by commas) in an array, so...

$string=explode(',',$string)

so, now i have this...

array='foo',' bar','blue ','bear','bla bla'

but, i don't want the extra white spaces at either end of any array element such as ' bar' or 'blue ', but i don't want to remove the space inside an element such as 'bla bla'.  Is there a function to do this?  RegEx skills are pathetic so I'm having trouble and str_replace(' ','',$string) obviously won't work :(



#2 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 27 July 2006 - 06:45 PM

trim().

#3 trq

trq
  • Staff Alumni
  • Advanced Member
  • 31,041 posts

Posted 27 July 2006 - 06:48 PM

Sorry... you might need to do something like...

$string=explode(',',$string)
foreach($string as $val) {
  $arr[] = trim($val);
}

That will give you your array all cleaned up in $arr.

#4 bcamp1973

bcamp1973
  • Members
  • PipPipPip
  • Advanced Member
  • 133 posts

Posted 27 July 2006 - 06:54 PM

Awesome!  Thank you!

#5 ryanlwh

ryanlwh
  • Staff Alumni
  • Advanced Member
  • 511 posts

Posted 27 July 2006 - 06:55 PM

shorter version
$string=explode(',',$string);
$arr = array_map('trim',$string);

Please use EDIT * 100...
Please use
or [php] * 1000...

PLEASE READ THE POSTED SOLUTIONS CAREFULLY * 1000000...

#6 xyph

xyph
  • Staff Alumni
  • Advanced Member
  • 3,712 posts
  • LocationSurrey, BC

Posted 27 July 2006 - 07:03 PM

trim() will have to be done to each element of the array. Rexgex wil lbe much better.

<?

$string = 'foo, bar,blue ,bear,bla bla,  omg  , test';
$replace = ',';

$fixed = preg_replace('/[\s]*(,)[\s]*/i', $replace, $string);

echo $fixed;

?>

Outputs : foo,bar,blue,bear,bla bla,omg,test
Everything you need to know about storing user-names and passwords
http://www.openwall....Users-Passwords
Blank Page? Try forcing errors to display
ini_set('display_errors',1);
error_reporting(-1);




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users