ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Mastering Regular Expressions in PHP

(Page 3 out of 4)

Another great example would be a telephone number. Say you want to verify telephone numbers and make sure they were in the correct format. Let's assume you want the numbers to be in the format of xxx-xxxxxxx. The code would look something like this:

// Good number
$good = "123-4567890";

// Bad number
$bad = "45-3423423";

// Let's check the good number
if (preg_match("/\d{3}-\d{7}/", $good)) {
        echo "Valid number";
} else {
        echo "Invalid number";
}

echo '';

// And check the bad number
if (preg_match("/\d{3}-\d{7}/", $bad)) {
        echo "Valid number";
} else {
        echo "Invalid number";
}

?>

The regex is fairly simple, because we use \d. This basically means "match any digit" with the length behind it. In this example it first looks for 3 digits, then a '-' (hyphen) and finally 7 digits. Works perfectly, and does exactly what we want.

« Previous: An Example
Next: What exactly is possible with Regular Expressions? »



Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. What are Regular Expressions?
  2. An Example
  3. Another Example
  4. What exactly is possible with Regular Expressions?
Bookmark Article
Download Article
PDF
Download this article as a PDF file