PHP Echo Tutorials

String Tidying Functions

Written by phpecho.com   

Consider an example where the user keys in a ZIP code and the application needs to fetch and display all hotels located in the region. Once the ZIP code is keyed in, then the application searches for hotels in the corresponding table with selection criteria equal to the zip code. What happens if the user has keyed in the zip code with an extra blank space at the end? How will the select query on the database return the record? It will not. This is where the string tidying functions are extremely useful. We will look at three functions - chop(), ltrim() and trim().

The chop() function is used to remove spaces at the end of a string. The ltrim() function removes spaces at the beginning of a string while the trim() function will remove spaces from both the beginning and the end. Consider an example:

<?php
$str = "Hello World ";
   echo ($str . ".");
   echo ('<br>');
   echo (chop($str) . ".");
?>

Save the above code in a file and run it on a web server.

The output when this program is executed will be like this:

Hello World .
Hello World.

Note the space at the end of "Hello World" in the first instance while in the second instance there is no space. The space has been chopped off.

Now let us look at an example to see how ltrim() works. Consider the code below. As earlier, copy paste this code into a file and run it on your web server.

<?php
$str = " Hello World";
   echo ("." . $str);
   echo ('<br>');
   echo ("." . ltrim($str));
?>

When this program is executed, the out put is

. Hello World
.Hello World

When the ltrim function is used, the spaces at the beginning of the string are removed.

Now, we take another example to show how the trim function works. Again, execute the code below on the web server.

<?php
$str = " Hello World ";
   echo ("." . $str . ".");
   echo('<br>');
   echo ("." . trim($str) . ".");
?>

The output for this program is

. Hello World .
.Hello World.

trim() function removes the space from both the start and end of the string.

Using the three functions described above, you should be able to tidy up user input with respect to unexpected spaces in them.