Tag Archives: regex

PHP: preg_match Give Names to the Matches

So Called – Subpatterns

Patterns - preg_match

In PHP 5.2.2+ you can name the sub patterns returned from preg_match with a specific syntax.

Named subpatterns now accept the syntax (?<name>) and (?’name’) as well as (?P<name>). Previous versions accepted only (?P<name>)

This is extremely helpful, when dealing with long patterns. As you may know you can simply use the “old school” way and to call the matches by their number based index:

    $haystack = '01 Jan 1970';
    $pattern = '/(\d{1,2})\ (Jan|Feb)\ (19\d\d)/';
 
    preg_match($pattern, $haystack, $matches);
 
    print_r($matches);

Although it may look difficult to maintain, now you can simply name the sub patterns of preg_match and to call them with their associative array keys. This is more clear when writing code and it’s definitely more maintainable.

    $haystack = '01 Jan 1970';
    $pattern = '/(?<day>\d{1,2})\ (?<month>Jan|Feb)\ (?<year>19\d\d)/';
 
    preg_match($pattern, $haystack, $matches);
 
    print_r($matches);
 
    // now there's $matches['day'], $matches['month'] ...

Perl Regular Expressions

For everyone who did write a code someday comes the question of using regular expressions. Almost everybody has heart about automatic and regular languages. Assume you have all word for a given languages, which means all possible combination between the letters of a given alphabet. For all these possible word only few construct the “language” as we know this term. Of course there’s also need of grammatic, etc. But however we have the set of words in a given language.

Than comes the task to find those of the words of the language that match a given condition. In fact the regular expressions are a powerful tool to do this job.

Using PHP you can use preg_ functions, which will perform a perl regular expressions match. In my case I had to find in about 180 .html files specific words.

Assume the files contain something like:

<!-- wellformed html comment -->
<tr>
<td class="classname1"><img ...></td>

<td class="classname2">

<a ... >

Word to match

</a>

</td>

</tr>

<tr>

<td ...></td>

<td ...></td>

</tr>

<!--wellformed html comment-->

The regular expressions for preg_replace function I used was something like this:

'/^[t|s]*<tr>.*?$n^.*?<td.*?</td>.*?$n.*?
<td.*?$n.*?<a.*?>.*?$n.*?Word  to  match.*?$n.*?</a>.*$n.*?</td>.*$n.*?
</tr>.*$n.*?<tr.*$n.*?<td.*$n.*?<td.*$n.*?</tr>/m'

… and it worked for me. In fact if you use ‘s’ instead of ‘m’ modifier that’s gonna be you mistake cause of the multiple matches before the current tag you want to match.