Bob Cavezza
Bob Cavezza

Reputation: 2850

How to detect if string contains 1 uppercase letter in PHP

Couldn't find a function for this. I'm assuming I need to use regex?

I'm trying to do html redirects in php in cases where the url contains at least 1 upper case letter.

example: http://www.domain.com/Michael_Jordan needs to be redirected to http://www.domain.com/michael_jordan - only problem is I can't seem to find a script to detect if at least 1 capital letter exists.

Upvotes: 36

Views: 52115

Answers (5)

inf3rno
inf3rno

Reputation: 26129

preg_match_all('%\p{Lu}%u', 'aA,éÁ,eE,éÉ,iI,íÍ,oO,óÓ,öÖ,őŐ,uU,úÚ,üÜ,űŰ', $m);
echo '<pre>';
var_dump($m);
echo '</pre>';

Tested with hungarian utf-8 characters, [A-Z] is for latin1 only.

Upvotes: 4

RageZ
RageZ

Reputation: 27313

Some regular expression should be able to the work, you can use preg_match and [A-Z]

if(preg_match('/[A-Z]/', $domain)){
 // There is at least one upper
}

Upvotes: 64

johnbessa
johnbessa

Reputation: 86

Here is a simpler eg:

$mydir = "C:\Users\John" ;

print preg_match('/^[A-Z]:\.*/', $mydir, $match )."\n" ;
print $match[0]. " preg match \n" ;

Produces:

1
C: preg match

This suggests that the parens are not necessary --for one match, at least

Look at this to be more specific for your application: PHP to SEARCH the Upper+Lower Case mixed Words in the strings?

Upvotes: 0

Ateszki
Ateszki

Reputation: 2255

You can also try this

if (!ctype_lower($string)) {
    // there is at least une uppercase character
}

not sure if this is more efficient than the other two methods proposed.

Upvotes: 8

Tyler Eaves
Tyler Eaves

Reputation: 13121

if (strtolower($url) != $url){
  //etc...

Upvotes: 35

Related Questions