#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0

    Insert space before capitals


    I need to put a space before each capital letter, unless there is a capital before it.

    // Strings sent
    $string = "JobTitle";
    $string = "UserGUID";

    // Response required
    $string = "Job Title";
    $string = "User GUID";

    Any ideas?

    This works in PHP but not as efficient as preg_replace()

    PHP Code:
        function spacebeforecapital($text) {
            
    // Should be able to achieve this through the magical wizardy of preg_replace()
            
    $chars str_split($text,1);
            
    $first true;
            
    $prevchar " ";
            
    $response="";
            foreach(
    $chars as $char) {
                if (
    $first) {
                    
    $response $char;
                    
    $first false;
                }
                else {
                    if (
    preg_match('/[A-Z]$/'$char) && (!(preg_match('/[A-Z]$/'$prevchar)))) {
                        
    // Its a capital! and the previous character isn't a capital
                        
    $response += " ";
                    }
                    
    $response += $char;
                }
                
    $prevchar $char;
            }
            return (
    $response);
        } 
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,113
    Rep Power
    9398
    That's one crazy solution considering how you can do it with preg_replace() like
    PHP Code:
    preg_replace('/([^A-Z ])\B([A-Z])/''$1 $2'$string
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    3
    Rep Power
    0
    Originally Posted by requinix
    That's one crazy solution considering how you can do it with preg_replace() like
    PHP Code:
    preg_replace('/([^A-Z ])\B([A-Z])/''$1 $2'$string
    Brilliant! Thank you

    Regex is a bit of a mystery to me...

IMN logo majestic logo threadwatch logo seochat tools logo