Regular Expression on PHP
One of the good point of choosing PHP as your language in creating dynamic web applications is its versatility on string processing, like PERL which is the leading language for string processing, PHP provides a powerful functions and capability in dealing with string. I decided to do a collection of useful regular expressions used on web for certain string matching.
Here are the collections of regExpr:
Domain
"/^(http:\/\/)?([^\/]+)/i"
This will extract the host name from the URL
Example implementation
$url = "http://www.knicks49.com/aboutme/";
preg_match("/^(http:\/\/)?([^\/]+)/i",$url, $result);
$host = $result[2];
print $host;
The output is www.knicks49.com. Alternatively you can also use this expression to extract the last two segments of the domain name.
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $result);
print "domain name is: {$result[0]}";
The output will produce domain name is: knicks49.com
Date
/[0-1][0-9](\/|-|\.)[0-9]{2}(\/|-|\.)[0-9]{4}/
This will extract date formatted like (mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy)
/[a-zA-Z0-9]+(\.|-)?[a-zA-Z0-9]*@
[a-zA-Z]+[0-9,a-z,A-Z,.,-]*(\.){1}[a-zA-Z]{2,4}/
This will extract email address from a string, if you need a more strict email address expression you can do a little tweaking on after the “@” sign expression to include only valid domain names for example
(yahoo|gmail|msn)
Phone Number
/[2-9]{2}-[0-9]{3}-[0-9]{4}/
This will extract phone number formatted like 99-999-9999
URL Address
/(http[s]?:\/\/|ftp:\/\/)?(www\.)?[a-zA-Z0-9-\.]+ \.(com|org|net|mil|edu|ca|co.uk|com.au|gov)/
This will extract url address such as (www.domain.com, www.domain.com server.com)
You can also check the following sites, for more reference on regular expression:
weblogtoolscollection.com/regex/regex.php
www.roscripts.com/PHP_regular_expressions_examples-136.html
www.php.net/manual/en/ref.pcre.php
Bookmark This!








I am Filipino Web Developer, focusing on PHP in LAMP framework. As a kid, I spent a lot of my time exploring computers and computer games from Atari to PS, from INTEL 80286 - CoreDuo. I am happily married, with two kids. Currently working in Japan as an IT Engineer.