Regular expressions are a powerful tool for examining and modifying text. preg_match is a powerful function of PHP that performs a regular expression match. Let’s have a short look on the syntax of preg_match before digging some interesting, practical and useful examples.
Syntax of preg_match
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
As my focus of this post is to share handy and useful examples of preg_match, so i am not going to discuss about the arguments of preg_match in detail. But i am sure you will learn them with the following examples professionally.
1. Find a String in a String
Find a string in a string can be done very easily by preg_match. Let’s have a look at the following two examples.
Useful Tip
The “i” after the pattern delimiter indicates a case-insensitive search
/* |--------------------- | Case Sensitive Search |--------------------- */ if ( preg_match("/cool/", "I love to share Cool things that help others. @lifeobject1") ) { echo "A match was found."; } else { echo "A match was not found."; } echo "<br />"; /* |--------------------- | Case Insensitive Search |--------------------- */ if ( preg_match("/cool/i", "I love to share Cool things that help others. @lifeobject1") ) { echo "A match was found."; } else { echo "A match was not found."; }
Output
Output of above examples will be,
A match was not found. A match was found.
2. Find a Word in a String
Find a word in a string is a hot and regular requirement in the php development. PHP beautifully provides this solution and we will achieve this task by the following two examples of preg_match.
Useful Tip
The “\b” in the pattern indicates a word boundary, so only the distinct
/* |--------------------- | Word "profession" is matched, and not a word partial like "professional" or "professionalism" |--------------------- */ if ( preg_match("/\bprofession\b/i", "I am Software Engineer by profession. @lifeobject1") ) { echo "A match was found."; } else { echo "A match was not found."; } echo "<br />"; /* |--------------------- | Word "profession" is matched, and not a word partial like "professional" or "professionalism" |--------------------- */ if ( preg_match("/\bprofession\b/i", "My professional ethic is sharing. @lifeobject1") ) { echo "A match was found."; } else { echo "A match was not found."; }
Output
Output of above examples will be,
A match was found. A match was not found.
3. Find Domain Name from URL
PHP developers often require to find a domain name from URL. preg_match provides a very easy solution. Let’s have a look into following examples.
Useful Tip
If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
/* |--------------------- | Get host name from URL |--------------------- */ preg_match( '@^(?:http://)?([^/]+)@i', "https://www.tutorialchip.com/category/php/", $matches ); $host = $matches[1]; echo "Host name is: " . $host; echo "<br />"; /* |--------------------- | Get last two segments of host name |--------------------- */ preg_match('/[^.]+\.[^.]+$/', $host, $matches); echo "Domain name is: " . $matches[0];
Output
Output of above examples will be,
Host name is: www.tutorialchip.com Domain name is: tutorialchip.com
4. Valid IP Address Check
preg_match makes the validity of IP address very easy. Let’s have a look into the following method which returns the validity of IP address professionally.
Useful Tip
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
/* |--------------------- | Valid IP Method |--------------------- */ function get_valid_ip( $ip ) { return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])" . "(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $ip ); } /* |--------------------- | Valid IP Example |--------------------- */ $ip = "192.168.1.1"; if ( get_valid_ip( $ip ) ) { echo $ip . " is valid."; } echo "<br />"; /* |--------------------- | Invalid IP Example |--------------------- */ $ip = "256.168.1.1"; if ( ! get_valid_ip( $ip ) ) { echo $ip . " is not valid."; }
Output
Output of above examples will be,
192.168.1.1 is valid. 256.168.1.1 is not valid.
5. US Phone Number Format Example
Getting a US phone number format is a tough task as user may input phone number in different formats. Let’s have a look at the power of preg_match. You will notice a usage of preg_replace for the sake of getting US phone number format.
/* |--------------------- | US Phone Number Format Regex |--------------------- */ $regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})' .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})' .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/'; /* |--------------------- | Different Formats |--------------------- */ $formats = array( '520-628-4539', '520.628.4539', '5206284539' , '520 628 4539', '(520)628-4539', '(520) 628-4539', '(520) 628 4539', '520-628.4539', '520 628-4539', '(520)6284539', '520.628-4539', '15206284539', '1 520 628 4539', '1.520.628.4539', '1-520-628-4539', '520-628-4539 ext.123', '520.628.4539 EXT 123 ', '5206284539 Ext. 5889', '520 628 4539 ext 8', '(520) 628-4539 ext. 456', '1(520)628-4539' ); /* |--------------------- | Let's Format Them |--------------------- */ foreach( $formats as $phoneNumber ) { if( preg_match($regex, $phoneNumber) ) { echo "Phone Number Matched " . $phoneNumber . " - US Format: " . preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber); echo "<br />"; } }
Output
Output of above examples will be,
Phone Number Matched 520-628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched 520.628.4539 - US Format: (520) 628-4539 ext. Phone Number Matched 5206284539 - US Format: (520) 628-4539 ext. Phone Number Matched 520 628 4539 - US Format: (520) 628-4539 ext. Phone Number Matched (520)628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched (520) 628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched (520) 628 4539 - US Format: (520) 628-4539 ext. Phone Number Matched 520-628.4539 - US Format: (520) 628-4539 ext. Phone Number Matched 520 628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched (520)6284539 - US Format: (520) 628-4539 ext. Phone Number Matched 520.628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched 15206284539 - US Format: (520) 628-4539 ext. Phone Number Matched 1 520 628 4539 - US Format: (520) 628-4539 ext. Phone Number Matched 1.520.628.4539 - US Format: (520) 628-4539 ext. Phone Number Matched 1-520-628-4539 - US Format: (520) 628-4539 ext. Phone Number Matched 520-628-4539 ext.123 - US Format: (520) 628-4539 ext. 123 Phone Number Matched 5206284539 Ext. 5889 - US Format: (520) 628-4539 ext. 588 Phone Number Matched 520 628 4539 ext 8 - US Format: (520) 628-4539 ext. 8 Phone Number Matched (520) 628-4539 ext. 456 - US Format: (520) 628-4539 ext. 456 Phone Number Matched 1(520)628-4539 - US Format: (520) 628-4539 ext.
6. Valid Email Address Regex
Email address validation is a regular requirement of PHP developers. Let’s see at following example.
Useful Tip
Because making a truly correct email validation function is harder than one may think, consider using with pure PHP through the filter_var function.
/* |--------------------- | Valid Email Address Regex |--------------------- */ function get_valid_email( $email ) { $regex = '/^([*+!.&#$¦\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i'; return preg_match($regex, trim($email), $matches); } /* |--------------------- | Different Emails |--------------------- */ $emails = array( 'my.name@gmail.com', 'another@gmail.co.uk', 'best@yahoo', 'hellomsn.net', 'long@123.org', '123.me.you@ymail.com', 'miss@yahoo.', ); /* |--------------------- | Let's Check Them |--------------------- */ foreach( $emails as $email ) { if( get_valid_email( $email ) ) { echo "Valid Email: " . $email; } else { echo "Invalid Email: " . $email; } echo "<br />"; }
Output
Output of above examples will be,
Valid Email: my.name@gmail.com Valid Email: another@gmail.co.uk Invalid Email: best@yahoo Invalid Email: hellomsn.net Valid Email: long@123.org Valid Email: 123.me.you@ymail.com Invalid Email: miss@yahoo.
Out of the Box: Email Address Validation with PHP filter_var function
Let’s see at following example of email address validation with PHP through the filter_var function.
/* |--------------------- | Valid Email Address filter_var |--------------------- */ function get_valid_email( $email ) { return filter_var( $email, FILTER_VALIDATE_EMAIL ); } /* |--------------------- | Different Emails |--------------------- */ $emails = array( 'my.name@gmail.com', 'another@gmail.co.uk', 'best@yahoo', 'hellomsn.net', 'long@123.org', '123.me.you@ymail.com', 'miss@yahoo.', ); /* |--------------------- | Let's Check Them |--------------------- */ foreach( $emails as $email ) { if( get_valid_email( $email ) ) { echo "Valid Email: " . $email; } else { echo "Invalid Email: " . $email; } echo "<br />"; }
Output
Output of above examples will be,
Valid Email: my.name@gmail.com Valid Email: another@gmail.co.uk Invalid Email: best@yahoo Invalid Email: hellomsn.net Valid Email: long@123.org Valid Email: 123.me.you@ymail.com Invalid Email: miss@yahoo.
7. Validate URL Regular Expression
We can use preg_match for the validation of any type of URL. Let’s have a look into the code snippet of PHP URL Valdation.
/* |--------------------- | Validate URL Regular Expression |--------------------- */ function get_valid_url( $url ) { $regex = "((https?|ftp)\:\/\/)?"; // Scheme $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP $regex .= "(\:[0-9]{2,5})?"; // Port $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor return preg_match("/^$regex$/", $url); } /* |--------------------- | Different URLs |--------------------- */ $urls = array( 'https://www.tutorialchip.com/', 'https://www.tutorialchip.com/php-csv-parser-class/#tab-description', 'http://www.google.com/search?hl=en&source=hp&biw=1366&bih=515&q=chip+zero+wordpress+theme&aq=f&aqi=&aql=&oq=', 'ftp://some.domaon.co.uk/', 'wwwhellocom', 'tcp://www.domain.org', 'http://wordpress.org', 'https:www.secure.net', 'https://.com', 'https://www.lock.cc', 'https://www.tutorialchip.com' ); /* |--------------------- | Let's Check Them |--------------------- */ foreach( $urls as $url ) { if( get_valid_url( $url ) ) { echo "Valid URL: " . $url; } else { echo "Invalid URL: " . $url; } echo "<br />"; }
Output
Output of above examples will be,
Valid URL: https://www.tutorialchip.com/ Valid URL: https://www.tutorialchip.com/php-csv-parser-class/#tab-description Valid URL: http://www.google.com/search?hl=en&source=hp&biw=1366&bih=515&q=chip+zero+wordpress+theme&aq=f&aqi=&aql=&oq= Valid URL: ftp://some.domaon.co.uk/ Invalid URL: wwwhellocom Invalid URL: tcp://www.domain.org Valid URL: http://wordpress.org Invalid URL: https:www.secure.net Valid URL: https://.com Valid URL: https://www.lock.cc Valid URL: https://www.tutorialchip.com
I hope you have learned a bit, and these code snippets of preg_match will help you in your web projects. Don’t forget to write your valuable comments, and subscribe your email to be tuned with latest tutorials, themes and articles.
Thanks for such a great collection! I will really use this phone number format code to convert phone numbers.
Very useful… Thanks buddy 😉
thanks lot. Much useful to me
Thanks a lot for this detailed info
very usefull thanks buddy
Very good work! Thank u so much for sharing!
I used function for valid IP address and it is working very well. thanks a lot .