Converting string

Discussion in 'PHP' started by Triexa, Apr 24, 2007.

  1. #1
    Say I wanted to convert some_text_string to SomeTextString


    Would this be the most efficient way to do it?
    $string = 'some_text_string';
    $string = str_replace('_', ' ', $string);
    $string = ucwords($string);
    PHP:
    Likewise, what would be an efficient method to go the opposite way?
     
    Triexa, Apr 24, 2007 IP
  2. frawsty

    frawsty Peon

    Messages:
    134
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Your output is gonna be 'Some Text String'
     
    frawsty, Apr 24, 2007 IP
  3. ErectADirectory

    ErectADirectory Guest

    Messages:
    656
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I asked a similar question about a month ago. This would be extremely useful when wanting to use WikiWordLinks inside the body of the page, only separated. Please someone pay attention to this chap, and give us both an answer.
     
    ErectADirectory, Apr 24, 2007 IP
  4. frawsty

    frawsty Peon

    Messages:
    134
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    $string = 'some_text_string';
    $string = str_replace('_', ' ', $string);
    $string = ucwords($string);
    $string = str_replace(' ', '', $string);
    Code (markup):
    or stack it:

    $string = 'some_text_string';
    $string = ucwords(str_replace('_', ' ', $string));
    $string = str_replace(' ', '', $string);
    Code (markup):
     
    frawsty, Apr 24, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    EDIT: A bit too late...


    Give this a try. (untested)
    
    
    // Format
    $string = preg_replace('/_([a-z])/e', "strtoupper('$1')", $string);
    
    // Reverse
    $string = preg_replace('/[A-Z]/e', "'_' . strtolower('$0')", $string);
    
    PHP:
     
    nico_swd, Apr 24, 2007 IP
    ErectADirectory likes this.
  6. Triexa

    Triexa Active Member

    Messages:
    580
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #6
    Oops. I just forgot to include the final replacement in my example :)
     
    Triexa, Apr 24, 2007 IP
  7. ErectADirectory

    ErectADirectory Guest

    Messages:
    656
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    0
    #7
    OK, not the point of this thread but Nico solved for WikiWords also. Way to be, mad rep to you.

    $string = "ErectADirectoryIsAGeek" ;
    // Reverse
    $string = preg_replace('/[A-Z]/e', "' ' . '$0'", $string);
    echo $string . "<br /><br />" ;
    // prints Erect A Directory Is A Geek 
    PHP:
     
    ErectADirectory, Apr 24, 2007 IP