15 PHP regular expressions for web developers

Posted on Jul 27, 2009

Regular expressions are a very useful tool for developers. They allow to find, identify or replace text, words or any kind of characters. In this article, I have compiled 15+ extremely useful regular expressions that any web developer should have in his toolkit.

Getting started with regular expressions

For many beginners, regular expressions seems to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics:

Enlight a word from a text

This very useful regular expression find a specific word in a text, and enlight it. Extremely useful for search results.

$text = "Sample sentence from KomunitasWeb, regex has become popular in web programming. Now we learn regex. According to wikipedia, Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor";
$text = preg_replace("/b(regex)b/i", '<span style="background:#5fc9f6">1</span>', $text);
echo $text;

Enlight search results in your WordPress blog

As I just said that the previous code snippet could be very handy on search results, here is a great way to implement it on a WordPress blog. Open your search.php file and find the the_title() function. Replace it with the following:

Remove repeated punctuation

Matching a XML/HTML tag

This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL.

Checking password complexity

This regular expression will tests if the input consists of 6 or more letters, digits, underscores and hyphens. The input must contain at least one upper case letter, one lower case letter and one digit.

WordPress: Using regexp to retrieve images from post

As I know many of you are WordPress users, you’ll probably enjoy that code which allow you to retrieve all images from post content and display it. To use this code on your blog, simply paste the following code on one of your theme files.

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^>]* />~';
// Run preg_match_all to grab all the images and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);
if ( $iNumberOfPics > 0 ) {
// Now here you would do whatever you need to do with the images
// For this example the images are just displayed
for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
echo $aPics[0][$i];
};
};
endwhile;
endif;
?>