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

preg_match

Tests whether a regex matches a string; retrieves match data

preg_match_all

Retrieves match data

preg_replace

Replaces matches with replacement text in a copy of the input string

preg_replace_callback

Calls a callback function for each match in the string

preg_split

Splits the input string into an array of substrings

preg_grep

Selects array elements matching or not matching the regex

preg_quote

Escapes regex metacharacters in a string

These functions are not part of preg; they are developed in this chapter.

preg_match

A version of preg_match distinguishing no match from an empty match

preg_regex_to_pattern

Creates a preg pattern string from a regex string

preg_pattern_error

Checks a preg pattern string for syntax errors

preg_regex_error

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