PHP Regular Expressions Examples

$str = “image_215_345.jpg”;

$re = “image_([0-9]+)_([0-9]+).([a-zA-Z]+)”;
$matches = array();
ereg($re, $str, $matches);

list($nothing, $first_number, $first_number, $ext) = $matches;

/////////////////////////////////////////////////////////////////////

$str = “2007-12-10 10:32:00″; //MySQL datetime format
$re = “([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})”;

$matches = array();
ereg($re, $str, $matches);

list($nothing, $year, $month, $day, $hour, $minute, $second) = $matches;

/////////////////////////////////////////////////////////////////////

Apache Server Log

$line = ’200.70.120.24 – - [09/Dec/2007:04:28:10 +0000] “GET /wp-content/themes/lancet/images/newlogo.jpg HTTP/1.1″ 200 6047 “http://blogs.thelancet.com/” “Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Win 9x 4.90)”‘;
$re = “(.+) (.+) (.+) \[(.+)\] \”(.+)\” ([0-9]+) ([0-9]+) \”(.+)\” \”(.+)\”";
$matches = array();
ereg($re, $line, $matches);

/////////////////////////////////////////////////////////////////////

$re = “[.css|.swf|.gif|.png|.jpg|.js|.txt|.ico|.fla|.flv]“;
preg_match($re, $url);

return 1 if the $url points to a css, a swf…or a flv file.

/////////////////////////////////////////////////////////////////////

$line = “09/Dec/2007:04:08:41 +0000″;
$re = “([0-9]+/[a-zA-Z]{3}/[0-9]+):(.*)”;
ereg($re, $line, $matches);
$date = $matches[1];

/////////////////////////////////////////////////////////////////////

// $request => GET /?s=uric+acide%2BROS&x=15&y=10 HTTP/1.1
// $request => POST / HTTP/1.1
$re = “[GET|POST] (.+) (.+)”;
ereg($re, $request, $matches);

/////////////////////////////////////////////////////////////////////

$line = ‘<span class=”date”>Tuesday 22nd January</span>’;
$re = ‘<span class=”date”>([^\ .]*) ([^\ .]*) ([^\ .]*)</span>’;
ereg($re, $line, $matches);

list($nothing, $weekday, $day, $month) = $matches;

/////////////////////////////////////////////////////////////////////

This example strips excess whitespace from a string.

<?php
$str
= 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// This will be 'foo o' now
echo $str;
?>

/////////////////////////////////////////////////////////////////////

This prepares a string to be put into an URL, replacing with a dash all non-alphabetical characters

$pattern = “[^A-Za-z0-9]“;
$replacement = ‘-’;
echo ereg_replace ($pattern, $replacement, $str);

/////////////////////////////////////////////////////////////////////

// prepending ‘http://’ if it is not present
$url = preg_replace(‘/^[^https?:\/\/](.+)$/’, ‘http://$0′, $url);

/////////////////////////////////////////////////////////////////////

Getting all the URL’s in anchor tags whose class=l
$re = “/]/”;
$search = preg_match_all($re, $html, $matches);

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply