Online
 
Friday, 09 January 2009
 
 
More article:
Related Content:

Perl-Compatible Regular Expressions (PCRE)
 
Article Index
Perl-Compatible Regular Expressions (PCRE)
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
Page 8
Page 9
Page 10
 

Named Patterns

An excellent and very useful addition to PCRE is the concept of named capturing groups (which everybody always refers to as named patterns). A named capturing group lets you refer to a subpattern of your expression by an arbitrary name, rather than by its position inside the regular expression. For example, consider the following regex:

/^Name=(.+)$/

Now, you would normally address the (.+) subpattern as the first item of the match array returned by preg_match() (or as $1 in a substitution performed through a call to preg_replace() or preg_replace_all()).

That's all well and goodat least as long as you have only a limited number of subpatterns whose position never changes. Heaven forbid, however, that you should ever find yourself in a position to have to add a capturing subpattern at the beginning of a regex that already has six of them!

Luckily, this problem can be solved once and for all by assigning a "name" to each of your subpatterns. Take a look at the following:

/^Name=(?P<thename>.+)$/

This will create a backreference inside your expression that can be explicitly retrieved by using the name thename. If you run this regex through preg_match(), the backreference will be inserted in the match array both by number (using the normal numbering rules) and by name. If, on the other hand, you run it through preg_replace(), you can backreference it by enclosing it in parentheses and prefixing it with ?P=. For example:

preg_replace ("/^Name=(?P<thename>.+)$/", "My name is (?P=thename)", $value);
you may want to include an example of this functionality.


Tags: Add more tags...,
This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment. Tags: Simple PHP, Pear, Easy PHP, PHP Tutorial, PHP MySQL, XSLT, Sap Tutorial, CSS Tutorial, XSL FO Java, SQL Tutorial.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Natural 402
Statistic


Last Post

 
Top! Top!