Must know Regular Expressions with php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Must know Regular Expressions with php

Post by Saman » Mon Jul 18, 2011 10:41 pm

Here I'm posting a set of very useful regular expressions in php. 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.

Code: Select all

int preg_match (string $pattern, string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
  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.
    The “i” after the pattern delimiter indicates a case-insensitive search

    Code: Select all

    /*
    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

    Code: Select all

    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.
    The “\b” in the pattern indicates a word boundary, so only the distinct

    Code: Select all

    /*
    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

    Code: Select all

    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.
    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.

    Code: Select all

    /*
    Get host name from URL
    */
    preg_match( '@^(?:http://)?([^/]+)@i', "https://robot.lk/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

    Code: Select all

    Host name is: robot.lk
    Domain name is: robot.lk
  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.
    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.

    Code: Select all

    /*
    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.0.5";
    if ( get_valid_ip( $ip ) ) {
    	echo $ip . " is valid.";
    }
    
    echo "<br />";
    
    /*
    Invalid IP Example
    */
    $ip = "256.157.0.5";
    if ( ! get_valid_ip( $ip ) ) {
    	echo $ip . " is not valid.";
    }
    Output

    Code: Select all

    192.168.0.5 is valid.
    256.157.0.5 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.

    Code: Select all

    /*
    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

    Code: Select all

    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.
    Because making a truly correct email validation function is harder than one may think, consider using with pure PHP through the filter_var function.

    Code: Select all

    /*
    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(
    			'[email protected]',
    			'[email protected]',
    			'cool@yahoo',
    			'kholi.net',
    			'[email protected]',
    			'[email protected]',
    			'gem@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

    Code: Select all

    Valid Email: [email protected]
    Valid Email: [email protected]
    Invalid Email: cool@yahoo
    Invalid Email: kholi.net
    Valid Email: [email protected]
    Valid Email: [email protected]
    Invalid Email: gem@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.

    Code: Select all

    /*
    Valid Email Address filter_var
    */
    function get_valid_email( $email ) {
    	return filter_var( $email, FILTER_VALIDATE_EMAIL );
    }
    
    /*
    Different Emails
    */
    $emails = array(
    			'[email protected]',
    			'[email protected]',
    			'cool@yahoo',
    			'kholi.net',
    			'[email protected]',
    			'[email protected]',
    			'gem@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

    Code: Select all

    Valid Email: [email protected]
    Valid Email: [email protected]
    Invalid Email: cool@yahoo
    Invalid Email: kholi.net
    Valid Email: [email protected]
    Valid Email: [email protected]
    Invalid Email: gem@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 Validation.

    Code: Select all

    /*
    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://robot.lk/',
    			'https://robot.lk/viewtopic.php?f=41&t=2619',
    			'http://www.google.com/#sclient=psy&hl=en&source=hp&q=robotlk&aq=f&aqi=&aql=&oq=&pbx=1&bav=on.2,or.r_gc.r_pw.&fp=97eede9ed711c932&biw=1920&bih=895',
    			'ftp://some.domaon.com/',
    			'wwwwelcomecom',
    			'tcp://www.domain.com',
    			'http://wordpress.org',
    			'https:www.secure.net',
    			'https://.com',
    			'https://www.lock.com',
    			'https://robot.lk');
    
    /*
    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

    Code: Select all

    Valid URL: https://robot.lk/
    Valid URL: https://robot.lk/viewtopic.php?f=41&t=2619
    Valid URL: http://www.google.com/#sclient=psy&hl=en&source=hp&q=robotlk&aq=f&aqi=&aql=&oq=&pbx=1&bav=on.2,or.r_gc.r_pw.&fp=97eede9ed711c932&biw=1920&bih=895
    Valid URL: ftp://some.domaon.com/
    Invalid URL: wwwwelcomecom
    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.com
    Valid URL: https://robot.lk
Post Reply

Return to “PHP & MySQL”