Re: Separating words based on capital letter

From: Date: Tue, 24 Apr 2007 21:39:06 +0000
Subject: Re: Separating words based on capital letter
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-253625@lists.php.net to get a copy of this message
Dotan Cohen wrote:
I have some categories named in the database as such: OpenSource HomeNetwork I'd like to add a space before each capital letter, ideally not including the first but I can always trim later if need be. As I'm array_walking the database, I have each value at the moment I need it in a string $item. Other than pregging for A-Z how can I accomplish this? I haven't been able to get it down to less than 54 lines of code, which in my opinion means that I'm doing something wrong.
You could do this with one regular expression, but if you really want to avoid them here is a 'pure PHP' way: <?php $test = 'HomeNetworkTestThing'; $az = range('A','Z'); $output = $test[0]; for ($i = 1; $i < strlen($test); $i++) { if (in_array($test[$i], $az)) { $output .= " {$test[$i]}"; } else { $output .= $test[$i]; } } echo $output; ?> Cheers, Rich -- Zend Certified Engineer http://www.corephp.co.uk "Never trust a computer you can't throw out of a window"

« previous php.general (#253625) next »