Top 5 PHP Regular Expressions for Web Developers

Tuesday, September 20th, 2011 | PHP | 0 comments

There’s no doubt about it, regular expressions are flippin’ awesome. Here, I’ve compiled a list of five user-defined PHP functions that I use regularly when developing back-end applications. All of these functions make use of regular expression matching.

1.) Return Alphanumeric Only

A very handy regular expression that I like to use for cleaning up usernames. It takes a string and returns its alphanumeric equivalency:

<?php
function alphaNumeric($string) {
	return preg_replace("/[^a-zA-Z0-9]/", "", $string);
}
?>

Sample string: DanMarino#13!@#$
Returns: DanMarino13

2.) Validate Email Address

This regular expression will return true if the string passed is a valid email address:

<?php
function checkEmail($email) {
	return preg_match("/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i", $email);
}
?>

Sample string: test@example.com
Returns: 1 (true)

3.) Check for Valid URL

A nifty regular expression that will return true if the given string is a valid URL:

<?php
function checkURL($url) {
	return preg_match("/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/", $url);
}
?>

Sample string: http://www.google.com
Returns: 1 (true)

4.) Check for Valid Hex Code

I often use this regular expression when developing sites that allow users to customize themes with hex codes. It will return true if a valid hex code is provided:

<?php
function checkHexCode($hex_code) {
	return preg_match("/^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/", $hex_code);
}
?>

Sample string: FF0000
Returns: 1 (true)

5.) Text Snippet, No Cut-Off In Middle of Word

Easily one of my favorite functions. This regular expression accepts a string and a character limit, and returns a shortened string without cutting off the middle of a word:

<?php
function textSnippet($str, $num) {
	$string_match = preg_match("/^([\s\S]){1," . $num . "}([\s\.])/",  $str, $matches);
	$shortened_string = $matches[0];
	return $shortened_string . '...';
}
?>

Sample string: Look at this crazy long line of text.
Returns: Look at this crazy…

 

Heyyyyy, Leave A Comment!

Submit