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:
Regular expressions syntax
Regular Expression
Will match…
foo
The string “foo”
^foo
“foo” at the start of a string
foo$
“foo” at the end of a string
^foo$
“foo” when it is alone on a string
[abc]
a, b, or c
[a-z]
Any lowercase letter
[^A-Z]
Any character that is not a uppercase letter
(gif|jpg)
Matches either “gif” or “jpeg”
[a-z]+
One or more lowercase letters
[0-9.-]
Ðny number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$
Any word of at least one letter, number or _
([wx])([yz])
wy, wz, xy, or xz
[^A-Za-z0-9]
Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})
Matches three letters or four numbers
PHP regular expression functions
Function
Description
preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote()
Quote regular expression characters
Validate domain name
Verify if a string is a valid domain name.
$url = "http://komunitasweb.com/"; if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) { echo "Your url is ok."; } else { echo "Wrong url."; }
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:
echo $title;
Now, just before the modified line, add this code:
<?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">\0</strong>', $title); ?>
Save the search.php file and open style.css. Append the following line to it:
strong.search-excerpt { background: yellow; }
Get all images from a HTML document
If you ever widhed to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.
$images = array(); preg_match_all('/(img|src)=("|')[^"'>]+/i', $data, $media); unset($data); $data=preg_replace('/(img|src)("|'|="|=')(.*)/i',"$3",$media[0]); foreach($data as $url) { $info = pathinfo($url); if (isset($info['extension'])) { if (($info['extension'] == 'jpg') || ($info['extension'] == 'jpeg') || ($info['extension'] == 'gif') || ($info['extension'] == 'png')) array_push($images, $url); } }
Remove repeated words (case insensitive)
Often repeating words while typing? This handy regexp will be very helpful.
$text = preg_replace("/s(w+s)1/i", "$1", $text);
Remove repeated punctuation
Same as above, but with punctuation. Goodbye repeated commas!
$text = preg_replace("/.+/i", ".", $text);
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.
function get_tag( $tag, $xml ) { $tag = preg_quote($tag); preg_match_all('{<'.$tag.'[^>]*>(.*?)</'.$tag.'>.'}', $xml, $matches, PREG_PATTERN_ORDER); return $matches[1]; }
Matching an XHTML/XML tag with a certain attribute value
This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div id=”header”>.
function get_tag( $attr, $value, $xml, $tag=null ) { if( is_null($tag) ) $tag = '\w+'; else $tag = preg_quote($tag); $attr = preg_quote($attr); $value = preg_quote($value); $tag_regex = "/<(".$tag.")[^>]*$attr\s*=\s*". "(['\"])$value\\2[^>]*>(.*?)<\/\\1>/" preg_match_all($tag_regex, $xml, $matches, PREG_PATTERN_ORDER); return $matches[3]; }
Matching hexadecimal color values
Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.
$string = "#555555"; if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) { echo "example 6 successful."; }
Find page title
This handy code snippet will find and print the text within the <title> and </title> tags of a html page.
$fp = fopen("http://www.catswhocode.com/blog","r"); while (!feof($fp) ){ $page .= fgets($fp, 4096); } $titre = eregi("<title>(.*)</title>",$page,$regs); echo $regs[1]; fclose($fp);
Parsing Apache logs
Most websites are running on the well-known Apache webserver. If your website does, what about using PHP and some regular expressions to parse Apache logs?
//Logs: Apache web server //Successful hits to HTML files only. Useful for counting the number of page views. '^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?.html?)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)200s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$' //Logs: Apache web server //404 errors only '^((?#client IP or domain name)S+)s+((?#basic authentication)S+s+S+)s+[((?#date and time)[^]]+)]s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"s+(?#status code)404s+((?#bytes transferred)[-0-9]+)s+"((?#referrer)[^"]*)"s+"((?#user agent)[^"]*)"$'
Replacing double quotes by smart qutotes
If you’re a typographer lover, you’ll probably love this regexp, which allow you to replace normal double quotes by smart quotes. A regular expression of that kind is used by WordPress on contents.
preg_replace('B"b([^"x84x93x94rn]+)b"B', '?1?', $text);
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.
'A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}z'
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; ?>
Generating automatic smileys
Another function used by WordPress, this one allow you to automatically replace a smiley symbol by an image.
$texte='A text with a smiley :-)'; echo str_replace(':-)','<img src="smileys/souriant.png">',$texte);