TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Looking for a better way to code this (http://www.talkphp.com/general/2601-looking-better-way-code.html)

benton 04-08-2008 12:56 AM

Looking for a better way to code this
 
I'm building a string dynamically. The result is that it may start with a dash (-), a space or a letter. I need to remove the first two, if they occur. The following code simulates the problem. If ran as is, it outputs XB - CX, which is correct (the X's are to show there aren't any spaces). But it seems unnecessary and overly complicated to use three trims in a row. The $array can come from a number of sources so while I could probably condition the string there, that would cause more code than the three trims. Can anyone see a better way to do this?

PHP Code:

$array = array();
$array['a'][0] = '';
$array['a'][1] = ' B';
$array['a'][2] = 'C';

$str implode(' ' .' - ' ' '$array['a']);
$str trim($str);
$str ltrim($str'-');
$str ltrim($str);
echo 
'X'.$str.'X'


delayedinsanity 04-08-2008 03:26 AM

PHP Code:

$array['a'][0] = '';
$array['a'][1] = ' B';
$array['a'][2] = 'C-';

$str trim(implode(' - '$array['a']), " -");
echo 
'X'.$str.'X'

should do the trick.

benton 04-08-2008 12:10 PM

Hmm, I had tried something like that, although with ltrim. Maybe I'm confused about the charlist argument. I tried
PHP Code:

ltrim($str"' '..'-') 

which seems to be the way the manual says to enter multiple characters. Is that not correct? Isn't the ' -' in yours just searching for that combination (space and dash)? I can see the code works but would like to understand the correct use of the command.

delayedinsanity 04-08-2008 02:10 PM

What it means by "With .. you can specify a range of characters." is a range of characters such as 1 to 9, or A to C, etc (1..9, or A..C, etc). For the basic characters you wish stripped, simply list one right after another, such as " -" or " \t_" etc. Nothing to seperate them, PHP will look at the characters one by one unless it sees .. to designate a range.
-m

benton 04-09-2008 02:25 AM

Thank you for the explanation. I thought they were making more complicated than needed when I was trying that. Now it all makes sense.


All times are GMT. The time now is 05:14 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0