PHP ─ Regular ExpressionRegular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for pattern-matching functionality. Using regular expression you can search a particular string inside another string, you can replace one string by another string and you can split a string into many chunks. PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of regular expression. You can use any of them based on your comfort.
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various elements (operators) are combined to form more complex expressions. The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or bag. Let us discuss a few concepts being used in POSIX regular expression. After that, we will introduce you to regular expression related functions. Brackets Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
Quantifiers The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a character sequence.
Following examples will clear your concepts about matching characters.
For your programming convenience several predefined character ranges, also known as character classes, are available. Character classes specify an entire range of characters, for example, the alphabet or an integer set:
PHP currently offers seven functions for searching strings using POSIX-style regular expressions:
Syntax
int ereg(string pattern, string originalstring, [array regs]);
Definition and Usage The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise. The search is case sensitive in regard to alphabetical characters. The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$email_id = "admin@tutorialspoint.com"; $retval = ereg("(\.)(com$)", $email_id); if( $retval == true ) { echo "Found a .com<br>"; } else { echo "Could not found a .com<br>"; } $retval = ereg(("(\.)(com$)"), $email_id, $regs); if( $retval == true ) { echo "Found a .com and reg = ". $regs[0]; } else { echo "Could not found a .com"; } ?> This will produce the following result −
Found a.com
Found a.com and reg=.com PHP ─ Function ereg_replace() Syntax
string ereg_replace (string pattern, string replacement, string
originalstring); Definition and Usage The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. The ereg_replace() function operates under the same premises as ereg(), except that the functionality is extended to finding and replacing pattern instead of simply locating it. Like ereg(), ereg_replace() is case sensitive. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$copy_date = "Copyright 1999"; $copy_date = ereg_replace("([0-9]+)", "2000", $copy_date); print $copy_date; ?> This will produce the following result −
Copyright 2000
PHP ─ Function eregi() Syntax
int eregi(string pattern, string string, [array regs]);
Definition and Usage The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. Eregi() can be particularly useful when checking the validity of strings, such as passwords. The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$password = "abc"; if (! eregi ("[[:alnum:]]{8,10}", $password)) { print "Invalid password! Passwords must be from 8 - 10 chars"; } else { print "Valid password"; } ?> This will produce the following result −
Invalid password! Passwords must be from 8 - 10 chars
PHP ─ Function eregi_replace() Syntax
string eregi_replace (string pattern, string replacement, string
originalstring); Definition and Usage The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$copy_date = "Copyright 2000"; $copy_date = eregi_replace("([a-z]+)", "&Copy;", $copy_date); print $copy_date; ?> This will produce the following result −
& Copy:2000
PHP ─ Function split() Syntax
array split (string pattern, string string [, int limit])
Definition and Usage The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in string. The optional input parameter limit is used to signify the number of elements into which the string should be divided, starting from the left end of the string and working rightward. In cases where the pattern is an alphabetical character, split() is case sensitive. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$ip = "123.456.789.000"; // some IP address
$iparr = split ("\.", $ip); print "$iparr[0] <br />"; print "$iparr[1] <br />" ; print "$iparr[2] <br />" ; print "$iparr[3] <br />" ; ?> This will produce the following result −
123
456 789 000 PHP ─ Function spliti() Syntax
array spliti (string pattern, string string [, int limit])
Definition and Usage The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive. Case-sensitive characters are an issue only when the pattern is alphabetical. For all other characters, spliti() operates exactly as split() does. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$ip = "123.456.789.000"; // some IP address $iparr = spliti ("\.", $ip, 3); print "$iparr[0] <br />"; print "$iparr[1] <br />" ; print "$iparr[2] <br />" ; print "$iparr[3] <br />" ; ?> This will produce only three strings as we have limited number of strings to be produced.
123
456 789.000 PHP ─ Function sql_regcase() Syntax
string sql_regcase (string string)
Definition and Usage The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a bracketed expression containing two characters. If the alphabetical character has both an uppercase and a lowercase format, the bracket will contain both forms; otherwise the original character will be repeated twice. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$version = "php 4.0"; print sql_regcase($version); ?> This will produce the following result −
[Pp][Hh][Pp]4.0
PERL Style Regular Expressions Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced in the previous POSIX section. Let us discuss a few concepts being used in PERL regular expressions. After that, we will introduce you with regular expression related functions. Metacharacters A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for large money sums using the '\d' metacharacter:/([\d]+)000/, Here \d will search for any string of numerical character. Following is the list of metacharacters which can be used in PERL Style Regular Expressions.
Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in multiple lines etc.
PHP offers the following functions for searching strings using Perl-compatible regular expressions:
Syntax
int preg_match (string pattern, string string [, array pattern_array], [, int
$flags [, int $offset]]]); Definition and Usage The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns contained in the search pattern, if applicable. If this flag is passed as PREG_OFFSET_CAPTURE, for every occurring match the appendant string offset will also be returned Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$line = "Vi is the greatest word processor ever created!"; // perform a case-Insensitive search for the word "Vi" if (preg_match("/\bVi\b/i", $line, $match)) : print "Match found!"; endif; ?> This will produce the following result −
Match found!
PHP ─ Function preg_match_all() Syntax
int preg_match_all (string pattern, string string, array pattern_array [, int
order]); Definition and Usage The preg_match_all() function matches all occurrences of pattern in string. It will place these matches in the array pattern_array in the order you specify using the optional input parameter order. There are two possible types of order –
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$userinfo = "Name: <b>John Poul</b> <br> Title: <b>PHP Guru</b>"; preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array); print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n"; ?> This will produce the following result –
John Poul
PHP Guru PHP ─ Function preg_replace() Syntax
mixed preg_replace (mixed pattern, mixed replacement, mixed string [, int limit
[, int &$count]] ); Definition and Usage The preg_replace() function operates just like POSIX function ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters. The optional input parameter limit specifies how many matches should take place. If the optional parameter $count is passed, then this variable will be filled with the number of replacements done. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$copy_date = "Copyright 1999"; $copy_date = preg_replace("([0-9]+)", "2000", $copy_date); print $copy_date; ?> This will produce the following result −
Copyright 2000
PHP ─ Function preg_split() Syntax
array preg_split (string pattern, string string [, int limit [, int flags]]);
Definition and Usage
The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern. If the optional input parameter limit is specified, then only limit number of substrings are returned. flags can be any combination of the following types –
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$ip = "123.456.789.000"; // some IP address $iparr = split ("/\./", $ip); print "$iparr[0] <br />"; print "$iparr[1] <br />" ; print "$iparr[2] <br />" ; print "$iparr[3] <br />" ; ?> This will produce the following result −
123.456.789.000
PHP ─ Function preg_grep() Syntax
array preg_grep ( string $pattern, array $input [, int $flags] );
Definition and Usage Returns the array consisting of the elements of the input array that match the given pattern. If flag is set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$foods = array("pasta", "steak", "fish", "potatoes"); // find elements beginning with "p", followed by one or more letters. $p_foods = preg_grep("/p(\w+)/", $foods); print "Found food is " . $p_foods[0]; print "Found food is " . $p_foods[1]; ?> This will produce the following result −
Found food is pasta Found food is
PHP ─ Function preg_quote() Syntax
string preg_quote ( string $str [, string $delimiter] );
Definition and Usage preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. Return Value
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
$keywords = '$40 for a g3/400'; $keywords = preg_quote($keywords, '/'); echo $keywords; ?> This will produce the following result –
\$40 for a g3\400';
|