Regular Expressions with PHP
3 May 2007A lot of PHP beginners tend to steer clear of regular expressions,
sometimes resorting to using an ugly mixture of str_replace and explode.
That's not surprising, regular expressions can be intimidating. Take a look at this pattern for validating an email address...
^[a-zA-Z][w.-]*[a-zA-Z0-9]@[a-zA-Z0-9][w.-]*[a-zA-Z0-9].[a-zA-Z][a-zA-Z.]*[a-zA-Z]$Fortunately, we can accomplish most programming tasks with much easier patterns.
This isn't meant to be a comprehensive guide, so I'll keep it very simple and just demonstrate how easy it is to grab the number of new links from dzone's homepage.
Here is the HTML source code surrounding the new links number.
<li><a href="/links/queue.html" >New links (217)</a></li>And here is the PHP code to fetch the number of new links.
<?php
// fetch the source of the homepage
$dzone = file_get_contents('http://www.dzone.com/');
// find matches for the pattern
preg_match('/<li><a href="/links/queue.html" >New links ((.*))</a></li>/', $dzone, $matches);
// print result
echo $matches[1];
?>
We use PHP's preg_match function to search in a string for a pattern.
As you can see, the pattern is just the surrounding HTML with all /)( characters escaped and "(.*)" replacing the number. Too easy.