Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Mastering Regular Expressions in PHP

By Dennis Pallett
2005-05-26


Another Example

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:
<?php

// 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 '<br />';

// 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.

Tutorial Pages:
» What are Regular Expressions?
» An Example
» Another Example
» What exactly is possible with Regular Expressions?


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1

Ask A Question
characters left.