Space on capital letter

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Space on capital letter

Post 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.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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..
User avatar
MarK (CZ)
Forum Contributor
Posts: 239
Joined: Tue Apr 13, 2004 12:51 am
Location: Prague (CZ) / Vienna (A)
Contact:

Post 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 />
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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);
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

thanks much everyone, i used feyds because of the acronymn abilities but thanks for all the input.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post 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);
Post Reply