PHP Tutorial :: Exercises (XIV)

PHP Exercise #29

Matching a phone number

Write a regular expression that matches a phone number either if it has or doesn't has parentheses around the provincial code, and it has each of its parts separated by spaces, hyphens or dots. The regular expression should match with phone numbers written like this:

(718) 498-1043

(718) 498 1043

718 498 1043

718 498-1043



// This regular expression matches with:
// an optional literal (
// three digits
// an optional literal )
// a hyphen, a space or a dot
// three digits
// a hyphen, a space or a dot
// four digits
// ^ and $ match the expression only with strings that solely contain
// a phone number and not any additional text

^\(?\d{3}\)?[- \.]\d{3}[- \.]\d{4}$

PHP Exercise #30

Matching letters and numbers

Write a expression that checks that the input sent from a form field named 'username' contains only letters and numbers.

if (! preg_match('/^[a-z0-9]$/i', $_POST['username'])) {
$_errors[] = "Usernames must contain only letters or numbers.";

PHP Exercise #31

Matching specific fields

Write a program that recovers weather forecast data from and analyze that page with a regular expression to obtain the current temperature.

$zip = 98052;
$url = '' . $zip;
$weather_page = file_get_contents($url);
if (preg_match('@<br><br>(-?\d+)°F<br>\((-?\d+)°C\)</td>@',
$weather_page, $matches)) {
// $matches[1] is the temperature in Fahrenheit
// $matches[1] is the temperature in Celsius
print "The current temperature is $matches[1] degrees.";
} else {
print "Can't get current temperature.";
Can't get current temperature.

PHP Exercise #32

Matching hyperlinks

Write a program that retrieves a remote webpage and prints a list of the hyperlinks that are on that page, by simply searching for the links that are like <a href="">Example page</a>, and not worrying about links that have any other attributes in the <a> tag.

$url = '';
$page = file_get_contents($url);
if (preg_match_all('@<a href="[^"]+">.+?</a>@', $page, $matches)) {
foreach ($matches[0] as $link) {
print "$link <br/>\n";