Home >> Latest Articles >> PHP Regular Expression Examples

PHP Regular Expression Examples

PHP Regular Expression Examples: Regular expression is 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 Expression and functions that might be helpful for any PHP developer.
What's regular expressions?

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, PHP Regular Expression 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 Expression codes, first we see the basics:

 1 abc… Letters
 2 123… Digits
 3 \d Any Digit
 4 \D Any Non-digit character
 5 . Any Character
 6 \. Period
 7 [abc] Only a, b, or c
 8 [^abc] Not a, b, nor c
 9 [a-z] Characters a to z
 10 [0-9] Numbers 0 to 9
 11 \w Any Alphanumeric character
 12 \W Any Non-alphanumeric character
 13 {m} m Repetitions
 14 {m,n} m to n Repetitions
 15 * Zero or more repetitions
 16 + One or more repetitions
 17 ? Optional character
 18 \s Any Whitespace
 19 \S Any Non-whitespace character
 20 ^…$ Starts and ends
 21 (…) Capture Group
 22 (a(bc)) Capture Sub-group
 23 (.*) Capture all
 24 (abc|def) Matches abc or def
Let’s have useful and reusable PHP Regular Expression code 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){ 
    if(preg_match('/^[^v]+v.(.{11}).*/',$url,$matches)){ 
        return 'http://img.youtube.com/vi/'.$matches[1].'/'.$index.'.jpg'; 
    }elseif(preg_match('/youtube.com\/user\/(.*)\/(.*)$/',$url,$matches)){ 
        return 'http://img.youtube.com/vi/'.$matches[2].'/'.$index.'.jpg'; 
    }else{ 
        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); 
    if(!is_null($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&lt;/ 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'; //Define here your words to censor separated by comma 
    $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.
$regex = "([a-z0-9_.-]+)". # name 
    "@". # at 
    "([a-z0-9.-]+){2,255}". # domain & possibly subdomains 
    ".". # period 
    "([a-z]+){2,10}"; # domain extension 
$eregi = eregi_replace($regex, '', $email); 
$valid_email = empty($eregi) ? true : false;
IP Address Validation
A simple method of validating an IP address using PHP and regular expressions.
$string = "255.255.255.255"; 
if (preg_match( 
    '/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', 
    $string)) { 
    echo "IP address is good."; 
}
Zip Code Validation
This is a simple method of validating a 9-digit zip code using PHP and regular expressions.
$string = "12345-1234"; 
if (preg_match('/^[0-9]{5}([- ]?[0-9]{4})?$/', $string)) { 
    echo "zip code 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"&;gt;\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://example.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://example.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 code will add http:// to the URL if it’s not there.
if (!preg_match("/^(http|https|ftp):/", $_POST['url'])) { 
    $_POST['url'] = 'http://'.$_POST['url']; 
}
Full Stack Tutorials

Author | Blogger @FullStackTutorials | View all articles