15+ regular expressions for PHP developers

Regular expressions are really very useful which allows search, validation, finding, identifying or replacing text, words or any kind of characters. Here in this post, I've listed 15+ useful PHP regular expressions and functions that might be helpful for any PHP developer.

The main use of regular expressions (also called regex or regexp) is to search for patterns in a given string. These search patterns are written using a special syntax which a regular expression parser understands. For many developers, regular expressions seem to be hard to learn and use. But it's not as hard as we think. So before going into useful and reusable PHP regular expressions pres, first we see the basics:

Basics of Regular expressions

Regular ExpressionsDescription
zagThe string “zag”
^zag“zag” at the start of a string
zag$“zag” at the end of a string
^zag$“zag” 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.-]A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


Let’s have useful and reusable PHP regular expressions pre snippets:

Remove special characters from string

Useful PHP regex to remove special characters from string.
$value = preg_replace("/[^A-Za-z0-9]/","",$value);



Validate username

This is handy PHP regex to validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character. You could also change the minimum character and maximum character to any number you like.

$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
echo "Your username is ok.";
} else {
echo "Wrong username format.";



Creates a YouTube thumbnail

Creates a YouTube thumbnail URL from a YouTube video URL.
function youtube_video_thumbnail($url,$index=0){
return 'http://img.youtube.com/vi/'.$matches[1].'/'.$index.'.jpg';
return 'http://img.youtube.com/vi/'.$matches[2].'/'.$index.'.jpg';
return false;



Replace a URL with its domain name and create link

preg_replace("/http:\/\/([^\/]+)[^\s]*/", "$1", $text);



Add Missing Alt tags to Images

This is a useful PHP function. If an image in your content is missing the alt tag, it adds that posts title as the alt tag for the image.

function add_alt_tags($content)
global $post;
preg_match_all('/<img (.*?)\/ >/', $content, $images);
foreach($images[1] as $index => $value)
if(!preg_match('/alt=/', $value))
$new_img = str_replace('<img', '<img alt="'.get_the_title().'"', $images[0][$index]);
$content = str_replace($images[0][$index], $new_img, $content);
return $content;
add_filter('the_content', 'add_alt_tags', 99999);



Automatic Mailto Links

$string = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href="mailto:\\1">\\1</ a>', $text);
echo $string;



Censor bad words with regexp

This function uses the power of regexp to check if some bad word are on the text, also offers the posibility to change those word for something else.

function filtrado($texto, $reemplazo = false)
$filtradas = 'ding, shit';
$f = explode(',', $filtradas);
$f = array_map('trim', $f);
$filtro = implode('|', $f);
return ($reemplazo) ? preg_replace("#$filtro#i", $reemplazo, $texto) : preg_match("#$filtro#i", $texto) ;



Telephone Number Validation

A simple PHP regex of validating a telephone number using regular expressions
$string = "(232) 555-5555";
if (preg_match('/^\(?[0-9]{3}\)?|[0-9]{3}[-. ]? [0-9]{3}[-. ]?[0-9]{4}$/', $string)) {
echo "example 2 successful.";



Replaces all links within href

Replaces all links within href part of anchor in a HTML-String.

$pattern = '/(?<=href\=")[^]]+?(?=")/';
$replacedHrefHtml = preg_replace($pattern, $replacement, $html);



Email Validation Regex

This is a awesome PHP regex for full email validation.
$email = "abc123@sdsd.com";
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";



IP Address Validation

A simple method of validating an IP address using PHP and regular expressions.
$string = "";
if (preg_match(
$string)) {
echo "IP address is good.";



Zip pre Validation

This is a simple method of validating a 9-digit zip pre using PHP and regular expressions.

$string = "12345-1234";
if (preg_match('/^[0-9]{5}([- ]?[0-9]{4})?$/', $string)) {
echo "zip pre checks out";



Highlight a word in the content

$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;



Extract domain name from certain URL

By using this regex, you can extract domain from a prticular url.

$url = "http://phpzag.com/index.html";
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host;



Validate domain

This is useful PHP regex to check whether provided url is valid or not.

$url = "http://phpzag.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.";



Create URL Slug from Post Title

You can create user friendly post slugs from title string to use within URLs. This regular expression function replaces spaces between words with hyphens.

function create_slug($string){
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
echo create_slug('does this thing work or not');



Add http to URL

Some times we need to accept some url as input but users did not add http:// to it, this pre will add http:// to the URL if it’s not there.

if (!preg_match("/^(http|https|ftp):/", $_POST['url'])) {
$_POST['url'] = 'http://'.$_POST['url'];


Convert URLs within String into hyperlinks

This is realy a useful function that converts URLs and e-mail addresses within a string into clickable hyperlinks.

function makeLinks($text) {
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
'\1', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
'\1\2', $text);
$text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
'\1', $text);
return $text;


You may like these posts