Jump to content

Archived

This topic is now archived and is closed to further replies.

bcamp1973

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

Recommended Posts

ok, so i have a string...

[code]$string='foo, bar,blue ,bear,bla bla';[/code]

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

[code]$string=explode(',',$string)[/code]

so, now i have this...

[code]array='foo',' bar','blue ','bear','bla bla'[/code]

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 :(

Share this post


Link to post
Share on other sites
[url=http://php.net/trim]trim[/url]().

Share this post


Link to post
Share on other sites
Sorry... you might need to do something like...

[code=php:0]
$string=explode(',',$string)
foreach($string as $val) {
  $arr[] = trim($val);
}
[/code]

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

Share this post


Link to post
Share on other sites
shorter version
[code]$string=explode(',',$string);
$arr = array_map('trim',$string);[/code]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.