Brandon Smith
22Jan/120

Evaluating Regular Expressions in PHP

It goes without saying that there are obvious benefits to using server-side validation of forms.  From e-mail validation to username formatting, it's important to use regular expressions to make sure any data being passed is both secure and compatible with your SQL database.  It's also important to use server-side validation over client-side(ex. JavaScript) to prevent SQL injection or any other malicious behavior.

Below is a basic example of how to evaluate a regular expression using PHP.  IF you're somewhat familiar with the language, the code should be easy enough to follow.  Please feel free to use at your own discretion; remember once a field/string has been evaluated the options are endless when handling the results!

A live example of the following code can be found here.

NOTE: Please forgive the formatting in the following snippet.  This is a current limitation of the blog and the majority of the whitespace is formatted incorrectly.

--------------------------

<?php
#pull POST variable from form submission
$str = $_POST['str'];

#define the function run the regular expression for the string value submitted
function parseString($x){

  #define the regular expression and set as variable: will return 1 if true(validated) or null if
    #the requirements are not met

    $evaluated = eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $x);

    #echo the input string for the sake of seeing results
  echo $x;

    #evaulate the regular expression and return a message if true or false
if ($evaluated){
echo " You've entered a valid e-mail address.";
} else {
echo " Please enter a valid e-mail address.";
}
}
?>
<!DOCTYPE HTML>
<body>
    <?php
    #execute the parseString function and pass the form-submitted variable
    parseString($str);
?>
<br />
    <!-- html for the form submitting the field/string under question -->
<form method="POST" action="regex.php">
<input type="text" id="str" name="str" /><br />
<input type="submit" value="submit" id="submit" />
</form>
</body>
</html>

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.