Last word of string UpperCase

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rienh
    New Member
    • Aug 2010
    • 3

    Last word of string UpperCase

    Hello all, I try to accomplish the following.
    I have a string like: “volkswage n-golf-gti” **
    And I want it to change the string into:
    “Volkswage n Golf GTI” (last part completely uppercase)

    But I have some difficulties understanding preg_replace.
    Right now I have the following code:

    Code:
    <?php 
    $string = 'volkswagen-golf-gti'; 
    $string2 = ucwords(str_replace('-', ' ', $string)); 
    $string2 = preg_replace("/\s+\S+$/e", "strtoupper('\\1')", $string2); 
    echo $string2; 
    ?>
    Without line 4 enabled, the result of the echo $string2 is:
    Volkswagen Golf Gti (is wrong, last part is not completely uppercase)

    With line 4 enabled, the last part of the $string is removed
    so echo $string2 gives me :
    Volkswagen Golf
    How can I change the code so it select the last part of $string2 and makes that part uppercase? So the result of echo $string2; will be:
    Volkswagen Golf GTI

    ** $string can be anything, not only volkswagen-golf-gti
    Last edited by rienh; Aug 30 '10, 02:10 PM. Reason: type error
  • rienh
    New Member
    • Aug 2010
    • 3

    #2
    Thanks to the solution of NoDog for providing me the solution, and solving my problem. The following code, did do the trick for me.

    Code:
    $var = 'volkswagen-golf-gti';
    $regexp = array(
       '/-/' => ' ',
       '/.*/e' => 'ucwords("$0")',
       '/\b\S+$/e' => 'strtoupper("$0")'
    );
    $var2 = preg_replace(array_keys($regexp), $regexp, $var);
    echo $var2;
    Last edited by rienh; Sep 1 '10, 09:39 AM. Reason: type error

    Comment

    • kovik
      Recognized Expert Top Contributor
      • Jun 2007
      • 1044

      #3
      This could have been done without regex. Assuming that the delimiter between your words is a space, you break the string apart, set the last word to uppercase, and glue the string back together. I just built a quick little function for it. No regex, just array manipulation.

      Function:
      Code:
      function last_word_uppercase($sentence, $delimiter = ' ') {
          $words = explode($delimiter, $sentence);
          if (!empty($words)) {
              $lastWord = array_pop($words);
              $words[] = strtoupper($lastWord);
              return implode($delimiter, $words);
          }
      
          return strtoupper($sentence);
      }

      Usage:
      Code:
      $str = 'This is a sentence.';
      echo last_word_uppercase($str);

      Result:
      Code:
      This is a SENTENCE.

      Comment

      Working...