How to change string’s case with PHP functions and with CSS

Add a comment August 16th, 2009

For a PHP developer, working with databases, arrays, doing string manipulations, etc are common daily tasks. While working with strings, you may sometime require changing case of the sting from lower to upper and vice versa or even you may need to change each word’s case in the given string. You can achieve all these by using following 5 PHP built in functions or you can use CSS property text-transform. Lets start with PHP functions.

1. strtolower() – convert a complete string into lowercase.

Example:

<?php
  $text = "I Love You GOD";
  $text = strtolower($text);
  echo $str; // Prints: i love you god
?>

2. strtoupper() – convert a complete string into uppercase. Just opposite of strtolower()

Example:

<?php
  $text = "I Love You GOD";
  $text = strtoupper($text);
  echo $text; // Prints: I LOVE YOU GOD
?>

3. lcfirst() – Make a string’s first character lowercase.

Example:

<?php
  $text = "I Love You GOD";
  $text = lcfirst($text);
  echo $text; // Prints: i Love You GOD
  //Notice 'I' converted to 'i'.
?>

4. ucfirst() – Make a string’s first character uppercase. Just opposite of lcfirst().

Example:

<?php
  $text = "i love you god";
  $text = ucfirst($text);
  echo $text; // Prints: I love you god
?>

5. ucwords() – Uppercase the first character of each word in a string.

Example:

<?php
  $text = "i love you god";
  $text = ucwords($text);
  echo $text; // Prints: I Love You God
  //Notice 'i' , 'l' , 'y' and 'g' converted to 'I' , 'L' , 'Y' and 'G' respectively.
?>

Source: php.net

Alternately, You can use CSS to change the text case. Use text-transform property to change the case in three ways:

Lower case: Makes all text in lower case.

.lowerText{
  text-transform: lowercase;
}

Upper case: Makes all text in upper case.

.upperText{
  text-transform: uppercase;
}

Capitalize: Makes uppercase the first character of each word in a string. It works exactly the same way the ucwords() php’s function does.

.capitalizeText{
  text-transform: capitalize;
}
Share or Bookmark this Post:
  • StumbleUpon
  • Digg
  • Twitter
  • del.icio.us
  • Facebook
  • Mixx
  • MySpace
  • Reddit
  • Google Bookmarks
  • Yahoo! Buzz
  • Technorati
  • Live
  • DZone
  • Netvibes
  • RSS
  • Print

 

  1. No comments yet.Be the first ?
  1. No trackbacks yet.
Comments feed
Real Time Web Analytics