XML technologies / Regular expressions / PHP / The preg programming interface
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The interface to the regex engine in PHP is purely procedural (see Procedural and object-oriented approaches). It comprises the seven functions in the upper part of the following table. The lower part lists four useful functions developed later in this chapter.
Table: overview of PHP preg functions.
Function | Use | |
|---|---|---|
Tests whether a regex matches a string; retrieves match data | ||
Retrieves match data | ||
Replaces matches with replacement text in a copy of the input string | ||
Calls a callback function for each match in the string | ||
Splits the input string into an array of substrings | ||
Selects array elements matching or not matching the regex | ||
Escapes regex metacharacters in a string | ||
These functions are not part of preg; they are developed in this chapter. | ||
A version of | ||
Creates a preg pattern string from a regex string | ||
Checks a preg pattern string for syntax errors | ||
Checks a regex string for syntax errors | ||
What these functions exactly do depends largely on argument types and count, selected options, and regex mode modifiers. Before the details, let us examine some examples to see how regexes are used in PHP:
/* Überprüfen, ob das HTML-Tag ein <table>-Tag ist */
if (preg_match('/^<table\b/i', $tag))
print "Tag $tag ist ein <table>-Tag\n";/* Eingabe auf ganze Zahl testen */
if (preg_match('/^-?\d+$/', $eingabe))
print "Eingabe ist eine ganze Zahl\n";/* Titel aus dem <title>-Tag eines HTML-Strings extrahieren */
if (preg_match('{<title>(.*?)</title>}si', $html, $treffer))
print "Seitentitel: $treffer[1]\n";/* Zahlen in einem String von Fahrenheit in Celsius umrechnen */
$metrisch = preg_replace('/(-?\d+(?:\.\d+)?)/e', /* Muster */
'floor(($1-32)*5/9 + 0.5)', /* Ersatztext */
$string);/* Aus einem String mit einfachen CSV-Daten Array-Elemente erzeugen */
$werte_array = preg_split('!\s*,\s*!', $csv_string);In the last example, a string such as ‘Eene,●meene,●muh’ produces an array with three elements: ‘Eene’, ‘meene’ and ‘muh’.
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
back to top