In php to find any text, characters and matching as your own patterns or if anybody want there custom patterns, its all are done by using PHP Regular Expressions. Like searching , it can also does replacing words. The regular expressions tools are very important tools for web developers. It is mostly use for searchiing any text or content.
Regular Expressions symbol
To learn Php Regular expressions, need to learn about the basic symbol of regular expressions which are used in regular expressions. There are some symbols which must learn to complete the regular expressions. These symbols of regular expressions are listed below.
Pattern | Description |
^ | This( ^ ) symbol denoted started with the pattern. |
$ | This( $ ) symbol denoted ended with the pattern. |
. | This stop ( . ) symbol denoted a single character . |
? | This ( ? ) symbol denoted the precedding pattern zero or one |
+ | This ( + ) symbol denoted the precedding pattern one or more. |
* | This ( ? ) symbol denoted the precedding pattern zero or more |
| | This symbol ( | ) works like Boolean OR |
- | This ( - ) symbol denoted a range of elements |
() | This ( () ) symbol denoted the groups of patterns. |
[] | This ( [] ) symbol denoted the a single pattern between this third brackets.. |
{min,} | This denoted to minimum characters to more characterrs |
{,max} | This denoted to maximum characters |
{min,max} | This denoted to minimum to maximum characters. |
/i | This denoted to insensitive case characters |
[Bangladesh] | |
\d | Matches only single digits |
\D | Matching only no digits. |
\w | Matches any alpha numeric character including underscore (_) |
\W | Matches any non alpha numeric character excluding the underscore character |
\s | Matches whitespace character |
Regular Expressions symbol uses
After learning about these symbols, now you need to learn how to use these symbols and what effects. Regular expression symbols takes more effect if any symbol changes. So need to clear and ovserve it what effects take. Let's started
Pattern | Match Pattern | Not match pattern | Description |
Bangladesh | Bangaldesh | Bangladesh1, Others , Dhaka | Only contains the word "Bangladesh" |
^(Bangladesh) | Bangladesh is a wonderful country. | In the world, Bangladesh is situated at the southern part of Asia | Staring any sentence with word "Bangladesh" |
(Bangladesh)$ | We like Bangladesh. | Bangladesh is a wonderful country. | Ending with the word "Bangladesh" |
^(Bangladesh)$ | Bangladesh is like "Bangladesh" | Bangladesh is a wonderful country. We like Bangladesh |
Starting and Ending with the word "Bangladesh" |
(Bangladesh)/i | bangladesh,BanGlAdeSh | Bangladesh1 | Only contain the word "Banglaadesh" with capital or samll letter |
Banglades(h)* | Bangladeshhhh, Bangladesh | Banglades | Contains the letters one or more after "Banglades" |
Banglades(h)+ | Bangladesh, Banglades, Bangladeshh | Bangla, Banglladesh | Contains the letter zero or more time after "Banglades" |
Banglades(h)? | Bangladesh, Banglades | Bangladeshhh | Contains the letter zero or one time after "Banglades" |
Banglades(h){1} | Bangladesh | Bangladeshh,Bangladeh1 | Contains the letter one time after "Banglades" . |
Banglades(h){2,} | Bangladeshh, Bangladeshhh | Bangladesh | Contains the letter 2 or more time after "Banglades" |
Bangldes(h){1,6} | Bangladesh, | Banglades, Bangladeshhhhhhhhhhhhh | Contains the letter onr or more 6 times after "Banglades" |
^{5}$ | tajbi | taj, taj1 , tajbir | Any five characters combination letters, symbols or digit |
Bangla(desh)* | Contains "desh" one or more times after "Bangla" | ||
Bangladesh|Dhaka | Contains Bangladesh OR Dhaka | ||
[Bangladesh] | Combination of letters within braces | ||
[a-z] | a, az, ab, abc | Ab, AB | Contains any small letters |
[a-zA-Z] | ab, ABCd | ab1, abc16 | Contains any small and capital letter |
[a-zA-Z0-9] | ab12, AbcD2 | ab@,sD10! | Any digits and all capital and small letters |
[a-zA-Z0-9._-] | abcd.- | adcd@ | Any digits,all capital and small letters, dot, underscore and hyphen |
^[a-zA-Z0-9_]{1,}$ | avcd | @123456 | Contains any digits,all capital and small letters, dot, underscore and hyphen with minimum 1 characters |
^[a-zA-Z0-9_]{5,10}$ | abcdefg, bangla | ban | Contains any digits,all capital and small letters, dot, underscore and hyphen with 5 - 10 characters |
([wx])([yz]) | wy,wz,xy,yz | wxyz | Combinations of wx and yz. Like wy,wz,xy,yz |
([A-Z]{3}|[0-9]{4}) | dbc, 1234 | abcd, 012345 | Three capital letters or any 4 digits |
[a-z]+ | al | AB | Any small letters contains 1 or more letters |
[^(a-z)] | abul, bangle | Abul, Bnagle | Satrt with any small letter |
[^(az)] | abul, ziko | Abul, liko | Start with small letters a and z |
Regular Expressions functions
Function | Description |
preg_match() | The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. |
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. |
eregi() | Case insensitive regular expression match |
eregi_replace | Replace regular expression case insensitive |
ereg() | Case sensitive regular expression match |
ereg_replace | Replace regular expression |
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 |
preg_match_all() | The preg_match_all() function matches all occurrences of pattern in string. |
stristr() | |
Regular expression check using php Functions
Example : Check a word like "tajbir"
<?php $pattern = "/^(tajbir)$/"; $txt = "tajbir"; if (preg_match($pattern,$txt)) echo "Found"; else echo "Not Found"; ?> //Output: //Found
Searching the limited chareacters.
Example : search a word which contains only two to five characters.
<?php $pattern = "/^[a-zA-Z]{2,5}$/"; $txt = "taj"; if (preg_match($pattern,$txt)) echo "Found"; else echo "Not Found"; ?> //Output: //Found
Searching chareacters and specific symbols also.
Example : A word that contains only letters and dot sign
<?php $pattern = '/^[a-zA-Z.]{1,}$/'; $txt= "Bangla.desh-"; if (preg_match($pattern,$txt)) echo "Found"; else echo "Not Found"; ?> //Output: //Not Found
All characters ,digits and and combination of symbols search.
Example : A word that contains combinations 4 to 20 lettres,digits,hyphen,undescore, dot or any of the one.
<?php $pattern = '/^[a-zA-Z0-9_.-]{4,20}$/'; $txt= "Bangla.desh-"; if (preg_match($pattern,$TXT)) echo "Found"; else echo "Not Found"; ?> //Output: //Found
Some common PHP regular expressions for web developers
Some regular and common used php Regular Expressions are mentioned given below.<?php $pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/"; $email = "tajbir@yahoo.com"; if (preg_match($pattern,$email)) echo "Found"; else echo "Not Found"; ?>Check any email using regular expressions by eregi() in php
<?php $pattern = "^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$"; $email = "tajbir@yahoo.com"; if (eregi($pattern,$email)) echo "Found"; else echo "Not Found"; ?>
<?php $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."; } ?>Wordpress title search using regular expressions
<?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu','<strong class="search-excerpt">\0</strong>', $title); ?>Get all images from a html document
<?php $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); } } ?>Matching HEXA decimal values
$string = "#555555"; if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $string)) { echo "example 6 successful."; }Find page title tag
<?php $fp = fopen("http://www.catswhocode.com/blog","r"); while (!feof($fp) ){ $page .= fgets($fp, 4096); } $titre = eregi("Matching aany XML/HTML tag(.*) ",$page,$regs); echo $regs[1]; fclose($fp); ?>
<?php function get_tag( $tag, $xml ) { $tag = preg_quote($tag); preg_match_all('{<'.$tag.'[^>]*>(.*?)'.$tag.'>.'}', $xml, $matches, PREG_PATTERN_ORDER); return $matches[1]; } ?>Validating a url
<?php $pattern = "/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$/"; $url = "http://www.taslimblogger.com"; if (preg_match($pattern,$emurl)) echo "Found"; else echo "Not Found"; ?>Validate US number
<?php /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/ ?>
Check the password is weak or strong if a password is strong
Weak passwords are one of the quickest ways to get hacked. The following regexp will make sure that:
Passwords will contain at least (1) upper case letter
Passwords will contain at least (1) lower case letter
Passwords will contain at least (1) number or special character
Passwords will contain at least (8) characters in
Password maximum length should not be arbitrarily
<?php (?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$ ?>Get the code between php tag
<?php <\?[php]*([^\?>]*)\?> ?>Grab unclosed img tags As you probably know, the xhtml standard requires all tags to be properly closed. This regular expression will search for unclosed img tags. It could be easily modified to grab any other unclosed html tags.
<?php <img([^>]+)(\s*[^\/])> ?>This regex will find CSS attributes, such as background:red; or padding-left:25px;.
<?php \s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1} ?>
Thanks for sharing such a wonderful post with us . It would definitely help our developers... thanks.
ReplyDelete