1.7 Converting the Case of a String


You need to convert the case of a string.

Technique

Use strtoupper() , strtolower() , ucfirst() , and ucwords() :

 <?php setlocale (LC_CTYPE, ""); $str = "mary had a little lamb"; $str = strtoupper ($str); // MARY HAD A LITTLE LAMB $str = strtolower ($str); // mary had a little lamb $str = ucfirst ($str); // Mary had a little lamb $str = ucwords ($str); // Mary Had A Little Lamb ?> 

Comments

The natural instinct for many people is to use a regular expression search and replace to change the case of a character (or characters ) in a string. Instead, you should consider using the functions here, which are considerably faster than using a regular expression.

Another common mistake is to use a regular expression for case-insensitive string comparisons. Instead, consider the following method:

 if (!strcasecmp ($str1, $str2)) {     //.. case-insensitive match } 

Here we use the strcasecmp() function to perform a case-insensitive string comparison on $str1 and $str2 . This is much faster than using the more complex eregi () and preg_match() functions ” especially on larger strings.

Note

Note that all the functions do exactly what they say they do and nothing more. Consider the following:

 <?php $str = "wE WILL ROCK YOU"; $str = ucwords ($str); // $str is now WE WILL ROCK YOU ?> 

The ucwords() function converts the first letter of each word in your string to uppercase. It does not modify any other part of the string; for instance, it does not make everything else lowercase.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net