Page 1 of 1

Space on capital letter

Posted: Mon Jul 24, 2006 1:53 am
by shiznatix
Alright so I have a string like this: 'SavedSearches' and I want to turn it into 'Saved Searches' (notice the space). How do I do that? I don't even know where to begin.

Posted: Mon Jul 24, 2006 2:12 am
by Benjamin
Something like this..

Untested.

Code: Select all

$length = strlen($String);

$newString = null;

for ($i = 0; $i < $length; $i++) {
    if ((chr($String{$i}) > 64) && (chr($String{$i}) < 91)) {
        $newString .= ' ' . $String{$i};
    } else {
        $newString .= $String{$i};
    }
}

$newString = trim($newString);
Edit: Added trim after looking at the code again because it will put a space in front of the first character..

Posted: Mon Jul 24, 2006 4:25 am
by MarK (CZ)

Code: Select all

<?php

$strings = array("SavedSearches",
                 "devNetworkHomepage");

forEach ($strings as $item)
  echo ereg_replace("([a-z])([A-Z])", "\\1 \\2", $item)."<br />\r\n";

?>
php output wrote:Saved Searches<br />
dev Network Homepage<br />

Posted: Mon Jul 24, 2006 7:50 am
by feyd
I've been using this for a bit of time. It not only breaks apart strings like requested, but also nicely breaks out capped words (a.k.a. acronymns and such.)

Code: Select all

$name = preg_split('#([^A-Za-z]+|[A-Z]?[a-z]+)#', $name, -1, PREG_SPLIT_DELIM_CAPTURE);
$name = array_map('trim', $name);
$name = array_filter($name);
$name = implode(' ', $name);

Posted: Tue Jul 25, 2006 3:06 am
by shiznatix
thanks much everyone, i used feyds because of the acronymn abilities but thanks for all the input.

Posted: Wed Jul 26, 2006 7:05 am
by bokehman
Keeping it simple... Just use a zero width assertion and insert a space...

Code: Select all

$result = preg_replace('/(?=(?<=[a-z])[A-Z])/', ' ', $input);