Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

PHP Regular Expression

In this article we will see what is PHP Regular Expression and learn how to work with this function in web development.

PHP is a cross platform language. It is a server side scripting language. We can use it with different platform for different types of jobs. As it is coming from some older popular language so that this language also support some expression that expression is generally called Regular Expression and that is implemented in our programming languages with lot of uses.

A regular expression in short for regex or regexp is a special text string for unfolding a pursuit pattern. We are thinking regular expressions as wildcards on steroids. Now we are most likely aware with wildcard notations such as *.txt to find all text files in a file manager. Now we give *.jpg that is used to display all jpg format picture from the storage device. The regex equivalent is «.*\.txt» or «.*\.jpg». We are providing much more jobs with regular expressions. In a text editor like EditPad Pro or a specialized text processing tool like PowerGREP that we can use the regular expression <<\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b>> to search for an email address from the web. We know that email address is to be exact and proper. A very similar regular expression (replace the first \b with ^ and the last one with $) can be used by a programmer to check if the user entered a properly formatted email address. It is just like one line of code whether that code is written in Perl, PHP, Java, or .NET language or an assembly of other languages.

Supported Meta characters:

PHP language supports Meta character that Meta character is representing in various manners for our different job and also for our different programming logic and it is not easy to know all Meta character at the time of designing a program. So for that reason we try to deliver all types Meta characters with their meaning.

This Meta character is listed below as table wise.

Character Representations
Sequence Meaning
\a It is Alert (bell), x07.
\b It is the represent Backspace, x08, supported only in character class.
\e It is set for ESC character, x1B.
\n Newline, x0A.
\r It is generating Carriage return, x0D.
\f Form feed, x0C.
\t Horizontal tab, x09
\octal Character specified by a three-digit octal code.
\xhex Character specified by a one- or two-digit hexadecimal code.
\x{hex} Character specified by any hexadecimal code.
\cchar Named control character.

Table 1: Showing character representation

Character classes and class-like constructs
Class Meaning
[...] It is a single character listed or contained within a listed range.
[^...] It is a single character not listed and not contained within a listed range.
[:class:] That is a POSIX-style character class valid only within a regex character class.
. Any character except newline (unless single-line mode,/s).
\C One byte; however, this may corrupt a Unicode character stream.
\w Word/Alphabetic character, [a-zA-z0-9].
\d This is Digit character, [0-9].
\s It is Whitespace character, [\n\r\f\t ].
\W Non-word character, [^a-zA-z0-9_].
\D Non-digit character, [^0-9].
\S Non-whitespace character, [^\n\r\f\t ].

Table 2: Showing Character classes and class-like constructs

Anchors and zero-width tests
Sequence Meaning
^ Start of a string or after any newline if in multiline match mode,/m.
\A Start of search string, in all match modes.
$ End of search string or before a string-ending newline, or before any newline if in multiline match mode, /m.
\Z End of string or before a string-ending newline, in any match mode.
\z End of string, in any match mode.
\G Beginning of current search.
\b Word boundary; position between a word character (\w) and a non-word character (\W), the start of the string, or the end of the string.
\B Not-word-boundary.
(?=...) Positive look ahead.
(?!...) Negative look ahead.
(? Positive look behind.
(? Negative look behind.

Table 3: Showing Anchors and zero-width tests

Comments and mode modifiers
Modes Meaning
i This is Case-insensitive matching.
m ^ and $ match next to embedded \n.
s It is Dot (.) matches newline.
x It is Ignore whitespace and allows comments (#) in pattern.
U Inverts greediness of all quantifiers: * becomes lazy and *? greedy.
A Force match to start at search start in subject string.
D Force $ to match end of string instead of before the string ending newline. Overridden by multiline mode.
u Treat regular expression and subject strings as strings of multi byte UTF-8 characters.
(?mode) It is used to turn listed modes (imsxU) on for the rest of the sub expression.
(?-mode) It is use to turn listed modes (imsxU) off for the rest of the sub expression.
(?mode:...) I a mode (xsmi) on within parentheses.
(?-mode:...) It is generating mode (xsmi) off within parentheses.
(?#...) It is generating a substring as a comment.
#... Rest of line is treated as a comment in x mode.
\Q Quotes all following regex meta characters.
\E Ends a span started with \Q.

Table 4: Showing Comments and mode modifiers

Grouping, capturing, conditional and control
Sequence Meaning
(...) Group sub pattern and capture sub match into \1,\2,…
(?P…) Group sub pattern and capture sub match into named capture group, name.
\n Contains the results of the nth earlier sub match from a parentheses capture group or a named capture group
(?:...) That Groups sub pattern, but does not capture sub match.
(?>...) It is disallow backtracking for text matched by sub pattern.
...|... It is Try sub patterns in alternation..
* It is match 0 or more times
+ It is match 1 or more times.
? It is match 1 or 0 times.
{n} It is match exactly n times.
{n,} It is match at least n times.
{x,y} It is match at least x times but no more than y times.
*? It is match 0 or more times, but as few times as possible.
+? It is match 1 or more times, but as few times as possible.
It is match 0 or 1 time, but as few times as possible.
{n,}? It is match at least n times, but as few times as possible.
{x,y}? It is match at least x times, no more than y times, and as few times as possible.
*+ It is used to match 0 or more times, and never backtrack.
++ It is used to match 1 or more times and never backtrack.
?+ It is used match 0 or 1 times, and never backtrack.
{n}+ It is used to match at least n times, and never backtrack.
{n,}+ It is match at least n times, and never backtrack.
{x,y}+ It is match at least x times, no more than y times, and never back track.
(?(condition) ..|...) It is match with if-then-else pattern. The condition can be either the number of a capture group or a look ahead or look behind construct.
(?(condition) ...) It is match with if-then pattern. The condition can be either the number of a capture group or a look ahead or look behind construct

Table 5: Showing Grouping, capturing, conditional and control

Pattern-Matching Functions:

PHP generally give some standalone functions for pattern matching. When we are creating regular expression strings then we have to escape embedded backslashes; otherwise, if we are not doing this then the backslash is interpreted in the string already being sent to the regular expression engine.

Now we provide different function with their syntax and their meaning

Function Syntax Meaning
array preg_grep array preg_grep (string pattern, array input) Return array containing every element of input matched by pattern.
int preg_match_all int preg_match_all (string pattern, string subject, array matches [, int flags]) Search for all matches of pattern against string and return the number of matches.
int preg_match int preg_match (string pattern, string subject [, arraymatches [, int flags]]) Return 1 if pattern matches in subject, otherwise returns 0. If the matches array is provided, the matched substring is placed in matches[0] and any capture group matches are placed in subsequent elements. Starting character position of the match.
string preg_quote string preg_quote (string str [, string delimiter]) Return a str with all regular expression metacharacters escaped. Provide the delimiter parameter if you areusing optional delimiters with your regular expressionand need the delimiter escaped in str.
mixed preg_replace_callback mixed preg_replace_callback (mixed pattern, callbackcallback, mixed subject [, int limit]) Return text of subject with every occurrence of pattern replaced with the results of callback. The callback should take one parameter, an array containing the matched text and any matches from capture groups.
mixed preg_replace mixed preg_replace (mixed pattern, mixed replacement, mixedsubject [, int limit]) It is return text of subject with every occurrence of pattern replaced with replacement. If provided, the function performs no more than limit replacements.
array preg_split array preg_split (string pattern, string subject [, int limit [, int flags]]) It is return an array of strings broken around pattern.
preg_split( ) It is returns no more than limit substrings

Table 6: Showing different functions

A limit is the concept of “no limit”. Now we allow you to set flags. PHP support some Obtainable flags. That is given below

Flag Meaning
PREG_SPLIT_NO_EMPTY It is return only non-empty pieces
PREG_SPLIT_DELIM_CAPTURE It is used to return captured sub matches after each split substring
PREG_SPLIT_OFFSET_CAPTURE It is returning an array of two-element arrays where the first element is the match and the second element is the offset of the match in subject.

Table 7: Showing flags

This is simple code that is generate Match and capture group

Listing 1: Sample showing functions

//Match dates formatted like MM/DD/YYYY, MM-DD-YY,  ... 
$date1 = "11/19/1986";
$r = "!(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)!" ;
if (preg_match($r,$date,$matches) 
{
$m = $matches[1];
$d = $matches[2];
$y = $matches[3];
}

This function return 1 if pattern matches in subject, otherwise return 0. If the matches array is provided then the matched substring is placed in matches [0] and any capture group matches are placed in subsequent elements.

Conclusion

In the above circumstance we find out that this regular expression is no doubt an important feature for web technology as well as PHP programing. Generally we find out that at the time of pattern matching, searching email processing and also different processes can easily be handled through this regular expression. Here we see that different types of tables present features that help us lot at the time of software revolution. Hope you have learnt the PHP regular expressions and their usage.

You can also find out something about regular expressions in other languages, as Java.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login