How to get capital letters from a string?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

How to get capital letters from a string?

Post by hawleyjr »

What is the best way to get the capital letters from a string?


ex:

Code: Select all

<?php

$myString = 'HereIsMyStringMcDonald';

echo getCapitalLetters($myString );

//Would return:  HIMSMD


function getCapitalLetters($str){

        //extract capital letters and return
}
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

untested:?:

Code: Select all

function getCapitalLetters($str)
{
  if(preg_match_all('#([A-Z]+)#',$str,$matches))
    return implode('',$matches[1]);
  else
    return false;
}
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

Works awesome.

Thanks Feyd. I've noticed your typically the first to respond with regular expressions. Is this something you learned programming other languages?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Not really.. I just have some decent practice with them ;) They're my kinda language.. :D
Post Reply