Regular Expressions in PHP

June 17, 2007 by hejian

You need reading the Basic Syntax of Regular Expressions first.

Get host name from URL:

preg_match("/^(http://)?([^/]+)/i”,
“http://shpchp.3322.org/index.php”, $matches);
echo $matches[2];

Get last two segments of host name:

preg_match("/[^./]+.[^./]+$/”, “shpchp.3322.org”, $matches);
echo $matches[0];

Validate email addresses:

$user = '[a-zA-Z0-9_-.+^!#$%&*+/=?`|{}~']+’;
$domain = ‘(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]).?)+’;
$ipv4 = ‘[0-9]{1,3}(.[0-9]{1,3}){3}’;
$ipv6 = ‘[0-9a-fA-F]{1,4}(:[0-9a-fA-F]{1,4}){7}’;
echo preg_match(”/^$user@($domain|([($ipv4|$ipv6)]))$/”, “hejian.he@gmail.com”);

Validate URL:

echo preg_match("/^(http|https|ftp)://[a-z0-9/:_-_.?$,;~=#&%+]+$/i”, “http://shpchp.3322.org/index.php”);

Replace term with hyperlink:

$content = "<html>... LAMP ...</html>";
$term = "LAMP";
$url = "http://shpchp.3322.org";
$pettern = "/(<[^a][^<>]*>[^>]*)(” . preg_quot($term, ‘/’) . “[a-zA-Z]*)/i”;
$replacement = ‘${1}<a href=”‘ . $url . ‘”>${2}</a>’;
echo preg_replace($pattern, $replacement, $content);

Using /s to let the dot metacharacter in the pattern matches all characters, including newlines:

print preg_match ('/<div id="header">(.*)</div> <!-- #header -->/s', $referer, $matches);

Leave a Reply

You must be logged in to post a comment.

Wordpress template made by HeJian