Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder mlse's Avatar
    Join Date
    Mar 2005
    Posts
    624
    Thanks
    20
    Thanked 19 Times in 18 Posts

    preg_replace for capitalising?

    Hi all,

    I want to convert a string like "this_is_my_string" to "thisIsMyString".

    The closest I've got is:

    PHP Code:
    $mystr "this_is_my_string";
    print(
    preg_replace('{\_([a-z])}''strtoupper("$1")'$mystr)); 
    Which doesn't quite work! (try it). I need to get preg_replace to recognise the call to strtoupper, or some equivalent method.

    Any ideas?

    TIA,
    Mike.
    Die Welt ist ein Irrenhaus und hier ist die Zentrale!

  • #2
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    PHP Code:
    $new_string str_replace(' ','',strtoupper(str_replace('_',' ',$mystr))); 
    will do it

  • #3
    Senior Coder chump2877's Avatar
    Join Date
    Dec 2004
    Location
    the U.S. of freakin' A.
    Posts
    2,778
    Thanks
    19
    Thanked 155 Times in 146 Posts
    I dont know how to do that with regex, but this works:
    PHP Code:
    $mystr "this_is_my_string";
    $mystr_arr explode("_",$mystr);
    foreach (
    $mystr_arr as $k => $v) {
        if (
    $k != 0)
            
    $mystr_arr[$k] = ucfirst($v);
    }
    $mystr implode("",$mystr_arr);

    print 
    $mystr
    Regards, R.J.

    ---------------------------------------------------------

    Help spread the word! Like my YouTube-to-Mp3 Conversion Script on Facebook !! :)
    [Related videos and tutorials are also available at my YouTube channel and on Dailymotion]
    Get free updates about new software version releases, features, and bug fixes!

  • #4
    Senior Coder
    Join Date
    Aug 2003
    Location
    One step ahead of you.
    Posts
    2,815
    Thanks
    0
    Thanked 3 Times in 3 Posts
    PHP Code:
    $mystr 'this_is_my_string';
    print 
    preg_replace_callback('/_([a-z])/'create_function('$a''return strtoupper($a[1]);'), $mystr
    I'm not sure if this was any help, but I hope it didn't make you stupider.

    Experience is something you get just after you really need it.
    PHP Installation Guide Feedback welcome.

  • #5
    Regular Coder mlse's Avatar
    Join Date
    Mar 2005
    Posts
    624
    Thanks
    20
    Thanked 19 Times in 18 Posts
    GJay: errr ... no! Thanks anyway.

    chump2877: Thanks, but I was looking for a preg_replace solution.

    marek_mar: Joy!
    Die Welt ist ein Irrenhaus und hier ist die Zentrale!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •