Jump to content

Last word of a string UpperCase


itsrien

Recommended Posts

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

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

$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);

Link to comment
Share on other sites

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;
?>

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.