PHP Strings Primer - Preparing user input for comparisons
(Page 12 of 37 )
When we accept user input, it doesn't always come in the exact case we expect. Even if we specify to the user that they should input data in all lower (or upper) case, we know that we can't trust the user to do so. In fact, you shouldn't even ask your user to adhere to specific formatting guidelines. If data is required in a particular format, you as the programmer should format the data properly. Therefore, we should take measures to make sure that any comparisons against user supplied data are done correctly. One method of accomplishing this goal is to convert any user supplied data to lowercase; or uppercase depending on your preference.
The 'strtolower()' and 'strtoupper()' functions will make this task easy for us. All we need to do is pass the data from the user to one of these two functions and make our comparison. In the following example, we will assume that we are collecting user data from a HTML form. The form element we wish to compare against is named 'lastname'.
<?php if (strtolower ($_POST['lastname']) == 'smith') { Â Â Â // take some action } else { Â Â Â // take a different action } ?> |
Obviously we could have used the 'strtoupper()' function in the last example in place of 'strtolower()'. Other than changing the function, the only other change would be to capitalize the string we were comparing against so that it would become ''SMITH''.
Next: Capitalization >>
More Programming Basics Articles
More By Matt Wade