Posts Tagged ‘Regular Expression’

Regular Expressions in PHP

Sunday, June 17th, 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);

Basic Syntax of Regular Expressions

Sunday, June 17th, 2007 by hejian

“^The”: matches any string that starts with “The”;
“[^a-zA-Z]“: matches a string with a character that is not a letter;

“ab*”: a followed by zero or more b’s (”a”, “ab”, “abbb”, etc.);
“ab+”: same, but there’s at least one b (”ab”, “abbb”, etc.);
“ab?”: there might be a b or not;

“s*”: any whitespaces

Regular Expressions in VIM

Saturday, June 16th, 2007 by hejian

Find all the lines which dos contains the “abc”:
/^%(%(abc)@<!.)*$

Search the date string such as “2005-07-12″:
/[0-9]{4}-[0-9]{2}-[0-9]{2}
or:
/v[0-9]{4}-[0-9]{2}-[0-9]{2}

Remove the 39th field of a CSV string:
:%s/(([^,]*,){38})[^,]*,/1/

Find all the lines has “aaa”, and find the fourth “,”, then insert a “‘bbb’, ” at there:
:%s/(^[^(]*aaa[^(]*([^,]*,[^,]*,[^,]*,[^,]*,)/1 ‘bbb’,/g
this command will replace:
REPLACE INTO `aaa` VALUES (107, 101, ”, ”, ‘Thomas’, ‘Rykaceski’, ‘249 Bear Creek Road’, ”, ‘16055′, ‘Sarver’, ”, 223, 51);
with
REPLACE INTO `aaa` VALUES (107, 101, ”, ”, ‘bbb’, ‘Thomas’, ‘Rykaceski’, ‘249 Bear Creek Road’, ”, ‘16055′, ‘Sarver’, ”, 223, 51);

Wordpress template made by HeJian