WebReference.com - PHP and Regular Expressions 101 (2/5) | WebReference

WebReference.com - PHP and Regular Expressions 101 (2/5)

To page 1current pageTo page 3To page 4To page 5
[previous] [next]

PHP and Regular Expressions 101

Why use regular expressions?

If you're constantly creating functions to validate or manipulate portions of a string, then you might be able to scrap all of these functions and use regular expressions instead. If you answer yes to any of the questions shown below, then you should definitely consider using regular expressions:

Besides being unfavored methods for string validation and manipulation, the two points shown above can also slow your program down if coded inefficiently. Would you rather use this code to validate an e-mail address:

<?php
  function validateEmail($email)
  {
    $hasAtSymbol = strpos($email, "@");
    $hasDot = strpos($email, ".");
    if($hasAtSymbol && $hasDot)
      return true;
    else
      return false;
  }
  echo validateEmail("[email protected]");
?>

... or this code:

<?php
  function validateEmail($email)
  {
    return ereg("^[a-zA-Z]+@[a-zA-Z]+\.[a-zA-Z]+$", $email);
  }
  echo validateEmail("[email protected]");
?>

Sure, the first function looks easier and seems well structured, but wouldn't it be easier if we could validate an e-mail address using the one-lined version of the validateEmail function shown above?

The second function shown above uses regular expressions only, and contains one call to the ereg function. The ereg function always returns only true or false, indicating whether its string argument matched the regular expression or not.

Many programmers steer clear of regular expressions because they are (in some circumstances) slower than other text manipulation methods. The reason that regular expressions may be slower is because they involve the copying and pasting of strings in memory as each new part of a regular expression is matched against a string. However, from my experience with regular expressions, the performance hit isn't noticeable unless you're running a complex regular expression against several hundred lines of text, which is rarely the case when used as an input data validation tool.


To page 1current pageTo page 3To page 4To page 5
[previous] [next]

Created: March 4, 2002
Revised: March 4, 2002

URL: https://webreference.com/programming/php/regexps/2.html