PHP Tutor #4 – Fixing a String Case, trim, ucwords, strtolower

with No Comments

In this tutorial we will explore manipulating the case of a string, and how to clean up strings like names. in PHP Tutor #4 we learned how to put a literal string into a variable like this:

<?php
  $name = 'marie estebanie pelin';
?>

However, the problem with this is, it is all lower case! And what if the person entering it had added a space at the front or end of the string? That could mess up alphabetizing a list! Or what if we wanted to extract the initials, or what if we wanted just the first two letters of each name to make some kind of username? Let’s look at how we can manipulate the case as well as extract a few things from a Crazy Bird string. Assume someone entered the following. Notice the extra space at the ends!

<?php
  $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
?>

Trim White Spaces

You can trim white spaces (or any character) from the left, right or both ends of a string!

Let’s use trim or rtrim to get rid of the white spaces at the right.

<?php
 $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
 $crazy_bird_name = trim($crazy_bird_name);
// now it's = 'mArIe eStEbANIe pELIN'
?>

So now there is no space!

More Ideas:

  • ltrim() – Strip whitespace (or other characters) from the beginning of a string
  • rtrim() – Strip whitespace (or other characters) from the end of a string
  • str_replace() – Replace all occurrences of the search string with the replacement string

 

Start a Word with a Capitol Letter

<?php   $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
  $crazy_bird_name = trim($crazy_bird_name);
// now it's = 'mArIe eStEbANIe pELIN'
  $crazy_bird_name = ucwords($crazy_bird_name); 
// now it's = 'MArIe EStEbANIe PELIN'
?>

Two Lines Only

This could have been written with only two lines of code by combining the last two lines like this:

<?php
  $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
  $crazy_bird_name = ucwords( trim( $crazy_bird_name ) ); 
// now it's = 'MArIe EStEbANIe PELIN'
?> 

 

More Ideas:

Not Quite Right!

The above did make each word start with a uppercase letter, but it did not make them look like we wanted, human names! What we really wanted was for the first letter of each word to be uppercase and the rest of each word to be lowercase. So here is how we can do that…

<?php
 $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
 $crazy_bird_name = trim($crazy_bird_name);
// now it's = 'mArIe eStEbANIe pELIN'
$crazy_bird_name = strtolower($crazy_bird_name);
// now it's = 'marie estebanie pelin'
$crazy_bird_name = ucwords($crazy_bird_name);
// now it's = 'Marie Estebanie Pelin'
?> 

We can also write this shorter like this…

<?php
 $crazy_bird_name = ' mArIe eStEbANIe pELIN ';
 $crazy_bird_name = ucwords( strtolower( trim( $crazy_bird_name ) ) );

// now it's = 'Marie Estebanie Pelin'
?> 

 

 

Leave a Reply