XML technologies / Regular expressions / PHP / Detailed examples
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
These two examples conclude the chapter.
Processing CSV files with PHP
Here is the PHP version of the CSV example from The art of writing regular expressions (see Unrolling the loop for CSV data). The regex uses possessive quantifiers (see Possessive quantifiers) instead of atomic groups for clarity.
The regex itself is:
$csv_regex = '{
\G(?:^|,)
(?:
# Entweder ein Feld in Anführungszeichen ...
" # Öffnendes Anführungszeichen
( [^"]*+ (?: "" [^"]*+ )*+ )
" # Schließendes Anführungszeichen
| # ... oder ...
# ... ein ›nacktes‹ Feld ohne Kommas und Anführungszeichen.
( [^",]*+ )
)
}x';This regex processes $zeile in CSV format:
/* Regex anwenden, Zwischenresultate werden in $alle_treffer geschrieben. */
preg_match_all($csv_regex, $zeile, $alle_treffer);
/* Im Array $Resultate werden die einzelnen Feldinhalte aus $alle_treffer gesammelt. */
$Resultate = array ();
/* Alle Treffer abklappern ... */
for ($i = 0; $i < count($alle_treffer[0]); $i++)
{
/* Wenn im 2. Klammerpaar etwas aufgefangen wurde, ist das direkt der Feldinhalt. */
if (strlen($alle_treffer[2][$i]) > 0)
array_push($Resultate, $alle_treffer[2][$i]);
else
{
/* Ein Feld in Anführungszeichen. Maskierte Anführungszeichen zurückverwandeln. */
array_push($Resultate, preg_replace('/""/', '"', $alle_treffer[1][$i]));
}
}
/* Das Array $Resultate enthält nun die Feldinhalte. */Checking proper tag nesting
Finally, a problem touching many interesting points: checking whether XML (or XHTML or similar markup) tags are balanced: no orphan start/end tags, and proper nesting. We look for paired elements, text without tags, and abbreviated empty elements such as <br/>.
The regex is:
˹^((?:<(\w++)[^>]*+(?<!/)>(?1)</\2>|[^<>]++|<\w[^>]*/>)*+)$˼
Matching strings have no unmatched or improperly nested tags, subject to caveats discussed later.
It initially looks complex, but sensible decomposition helps. The outer parentheses and anchors ˹^(...)$˼ wrap the core and require a match to span the entire subject. The capture also lets the whole core recurse.
The core regex
The core has three alternatives, underlined separately above, enclosed in ˹(?:...)*+˼ to allow a sequence. They match paired elements, text without tags, and abbreviated empty elements.
The alternatives are mutually exclusive, so backtracking cannot find a match by handing text to another branch. A possessive * around the alternatives exploits this: after a branch matches, the regex engine does not backtrack.
For the same reason, branch order is irrelevant. I put the most likely first (see Most likely alternative first).
Examine the branches in turn:
Second branch: text without tags
The middle branch is simplest: ˹[^<>]++˼. It matches text without angle brackets, hence without tags. The possessive quantifier ˹(?:...)*+)˼ may seem excessive given the outer possessive quantifier, but I prefer the added safety. Possessive quantifiers usually improve efficiency, but can alter meaning, so consider them carefully; see Using atomic groups and possessive quantifiers.
Third branch: abbreviated empty elements
The third branch ˹<\w[^>]*/>˼ matches empty-element tags such as <br/> or <img .../>. They have a slash before the final bracket and no separate closing tag.
First branch: paired start and end tags
Finally, the most complex branch: ˹<(\w++)[^>]*+(?<!/)>(?1)</\2>˼
The first underlined part matches a start tag, capturing its name with ˹(\w++)˼, the regex's second capture. (The possessive quantifier on ˹\w++˼ matters; more on this later.)
˹(?<!/)˼ is negative lookbehind (see Lookahead; lookbehind), requiring that the character before ˹>˼ is not a slash. Thus the apparent start tag is not actually an empty tag like <hr/>, reserved for the third branch.
After the start tag, ˹(?1)˼ recursively applies the first capture, our core matching properly nested content. Then find the corresponding end tag, whose name was saved in capture two. The ˹</˼ at the beginning of ˹</\2>˼ ensures an end tag. The backreference ˹\2>˼ ensures the correct end tag, with the same name as the start. In case-insensitive markup such as HTML, add ˹(?i)˼ at the start, or use the i modifier.
Whew!
Possessive quantifiers
A few more words on the possessive quantifier in ˹\w++˼ in the first branch, ˹<(\w++)[^>]*+(?<!/)>˼. Without possessive quantifiers or atomic groups (see Atomic parentheses), I would append to (\w+) the construct ˹\b˼ : ˹<(\w+)\b[^>]*(?<!/)>˼.
The \b prevents partial tag-name matches by (\w+)˼, such as only ›li‹ in a ›<link>...</li>‹ tag. This leaves ›nk‹ outside the capture, causing backreference ˹\2˼ to use the wrong tag name.
Well-formed XML avoids this because \w+ greedily takes as many word characters as possible. With bad nesting, however, backtracking could return ›nk‹ and incorrectly accept ›<link>...</li>‹. Using ˹\b˼ prevents this.
PHP's preg engine supports possessive quantifiers, so use ˹(\w++)˼ for the same effect: no partial tag names.
XML in practice
XML is generally more complex. We must also handle XML comments, blocks of type CDATA (sections ), and XML processing instructions (processing instructions).
Add XML comments as a fourth branch, ˹<!–.*?–>;˼, ensuring dot matches any character, with ˹(?s)˼ or the s modifier.
Similarly, CDATA sections of the form <![CDATA[...]]> use another branch: ˹<!\[CDATA\[.*?]]>˼. Processing instructions such as ›<?xml●version="1.0"?>‹ use the additional branch ˹<\?.*?\?>˼.
An entity declaration has the form ›<!ENTITY...>‹ and is handled by ˹<!ENTITY\b.*?>˼. Similar XML structures follow this pattern; ˹<![A-Z].*?>˼ handles them all.
Some XML subtleties remain, but this covers almost all data. Together, the PHP snippet is:
$xml_regex = '{
^(
(?: <(\w++) [^>]*+ (?<!/)> (?1) </\2> # Paar von Tags, rekursiv
| [^<>]++ # Text ohne Tags
| <\w[^>]*/> # Leeres-Element-Tag, Kurzform
| <!--.*?--> # Kommentar
| <!\[CDATA\[.*?]]> # CDATA-Block
| <\?.*?\?> # Verarbeitungsinstruktionen (PIs)
| <![A-Z].*?> # Entity-Deklarationen usw.
)*+
)$
}sx';
if (preg_match($xml_regex, $xml_string))
echo "Korrekt verschachtelt.\n";
else
echo "Ungültige Verschachtelung.\n";Does it work for HTML?
Real-world HTML often cannot pass this check: unmatched or misnested tags, and characters not encoded as entities, such as ›<‹ and ›>‹. Even clean HTML has special cases: comments and <script> tags.
HTML comments are handled as in XML: ˹<!–.*?–>˼ with the s modifier.
The <script> elements may contain bare ›<‹ and ›>‹ characters. Allow anything between the opening <script...> and closing </script>: ˹<script\b[^>]*>.*?</script>˼. This branch is needed only if the <script> element contains angle brackets; otherwise the first branch handles its paired tags.
Here is the HTML version:
$html_regex = '{
^(
(?: <(\w++) [^>]*+ (?<!/)> (?1) </\2> # Paar von Tags, rekursiv
| [^<>]++ # Text ohne Tags
| <\w[^>]*/> # Leeres-Element-Tag, Kurzform
| <!--.*?--> # Kommentar
| <script\b[^>]*>.*?</script> # script-Element
)*+
)$
}isx';
if (preg_match($html_regex, $html_string))
echo "Korrekt verschachtelt.\n";
else
echo "Ungültige Verschachtelung.\n";
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln