itsrien Posted August 30, 2010 Share Posted August 30, 2010 Hello all, I try to accomplish the following. I have a string like: “volkswagen-golf-gti” ** And I want it to change the string into: “Volkswagen Golf GTI” (last part completely uppercase) But I have some difficulties understanding preg_replace. Right now I have the following 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 Quote Link to comment https://forums.phpfreaks.com/topic/212076-last-word-of-a-string-uppercase/ Share on other sites More sharing options...
litebearer Posted August 30, 2010 Share Posted August 30, 2010 Not tested but... $string = 'volkswagen-golf-gti'; $my_arrray = explode("-", $string); $my_count = count($my_array); $my_last = $my_count -1; $last_word = strtoupper($my_array[$my_last]); $my_array[$my_last] = $last_word; $i=0; $new_string = "": while($i <$my_count) [ $new_string = $new_string . " " . $my_array[$i]; $i++; } echo $new_string; Quote Link to comment https://forums.phpfreaks.com/topic/212076-last-word-of-a-string-uppercase/#findComment-1105230 Share on other sites More sharing options...
AbraCadaver Posted August 30, 2010 Share Posted August 30, 2010 $string2 = preg_replace('/([^ ]+)$/e', 'strtoupper("\\1")', ucwords(str_replace('-', ' ', $string))); // or // tried to get it in one line but having a brain cramp: $string2 = array_map('ucfirst', explode('-', $string)); array_push($string2, strtoupper(array_pop($string2))); $string2 = implode(' ', $string2); Quote Link to comment https://forums.phpfreaks.com/topic/212076-last-word-of-a-string-uppercase/#findComment-1105251 Share on other sites More sharing options...
itsrien Posted September 1, 2010 Author Share Posted September 1, 2010 Thanks you NoDog for providing me the solution, and solving my problem. The following code, did do the trick for me. <?php $var = 'volkswagen-golf-gti'; $regexp = array( '/-/' => ' ', '/.*/e' => 'ucwords("$0")', '/\b\S+$/e' => 'strtoupper("$0")' ); $var2 = preg_replace(array_keys($regexp), $regexp, $var); echo $var2; ?> Quote Link to comment https://forums.phpfreaks.com/topic/212076-last-word-of-a-string-uppercase/#findComment-1105999 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.