Perl Compatible Regular Expression(PCRE)

Friday, May 18, 2012 0 comments
Perl Compatible Regular Expression(PCRE)
Perl Compatible Regular Expressions (normally abbreviated as “PCRE”) offer a very powerful string-matching and replacement mechanism that far surpasses anything we have examined so far.

Delimiters
A regular expression is always delimited by a starting and ending character.
e.g.   /ab[cd]e/
Here "/" is the delimiter. The expression above will match both abce and abde.

Metacharacters
.       Match any character
ˆ       Match the start of the string
$      Match the end of the string
\s     Match any whitespace character
\d     Match any digit
\w    Match any “word” character


Quantifiers
A quantifier allows you to specify the number of times a particular character or metacharacter can appear in a matched string. There are four types of quantifiers:

*             The character can appear zero ormore times
+             The character can appear one or more times
?              The character can appear zero or one times
{n,m}      The character can appear at least n times, and no more than m.
                 Either parameter can be omitted to indicated a minimum limit
                with nomaximum, or a maximum limit without aminimum, but
                not both.

Using PCRE
First we need to create a regular expression using above rules. All  the combinations of string that can be generated from regular expression is valid.

for e.g.    /ab[c-e\d]/
This will match abc, abd, abe and any combination of ab followed by a digit.

Similarly, /a(bc.)e/
This expression will match the letter a, followed by the letters b and c, followed by
any character and, finally the letter e.

/a(bc.)+e/
This expression will match the letter a, followed by the expression bc. repeated one
or more times, followed by the letter e.

For given regular expression certain combinations are generated now how do we check than users input matches with the combinations or not, For that we will use the function preg_match.

$name = "Pratik Shrestha";
// Simple match
$regex = "/[a-zA-Z\s]/";
if (preg_match($regex, $name)) 
// Valid Name
echo "Valid";
}

In above code if the user input suppose user input is "Pratik Shrestha" and we need to check whether the input matches the pattern or not we pass it to the function preg_match.If it matches it will return true else false.Thus if pattern matches if condition will execute.

Hope you got some idea of regular expression.If you want to see one  practical use PCRE. Look at this.

Source
PHP ZEND BOOK


0 comments:

Post a Comment

Recent Posts

WebInfo

 

©Copyright 2011 WebInfo