XML technologies / Regular expressions / PHP / “Missing” preg functions / preg_regex_to_pattern

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

A regular expression stored in a string variable, perhaps from a configuration file or web form, must first be wrapped in delimiters before being used in a preg function as a Pattern argument.

 

The problem

In the simplest case, converting a regular expression to a Pattern argument requires only adding a slash at either end. For example, the regex string ›[a-z]+‹ becomes ›/[a-z]+/‹, a string usable as a Pattern argument.

Conversion becomes more complicated when the regex contains the delimiter character itself. If the regex string is ›^http://([^/:]+)‹, merely wrapping it in slashes produces ›/^http://([^/:]+)/‹; using this as a Pattern argument produces the error message “Unknown modifier /”.

As explained in the box The “Unknown Modifier” error, this message appears because the first two slashes are interpreted as delimiters, and everything afterward, here the third slash, as the start of the modifier list.

 

The solution

There are two ways to avoid this delimiter/modifier conflict. One is to choose a delimiter absent from the regex, certainly the most sensible approach when constructing a regex in a program. That is why I used braces as delimiters in the examples in The preg programming interface, preg_match: explanations and Examining match data.

But this approach can be difficult or impossible if the regex and its characters are not known in advance. When it comes from an external source, the second approach is preferable: choose a particular delimiter and escape any occurrences of it within the regex with a backslash.

Even that is trickier than it looks: several important edge cases must be considered. A trailing backslash, for example, needs special treatment so it does not escape the appended closing delimiter.

The following function takes a regex string and an optional modifier string and produces a Pattern string usable directly as a preg function’s Pattern argument. The code contains an alarming number of backslashes, escaping regex and PHP string metacharacters. It certainly is not easy to read. (For more on PHP single-quoted strings, see The pattern parameter).

/*
 * Verpackt einen ›nackten‹ Regex-String (und einen optionalen String mit Modifikatoren) so, dass
 * er als Pattern-Argument eingesetzt werden kann. Die Regex bekommt Begrenzungszeichen und
 * die Modifikatoren werden angehängt.
 */
function preg_regex_to_pattern($nackte_regex, $modifikatoren = "")
{
  /*
   * Die Regex muss in Begrenzungszeichen (wir verwenden einfache Schrägstriche) eingefasst
   * und die Modifikatoren angehängt werden. Wir müssen sicherstellen, dass alle nicht bereits 
   * maskierten Begrenzungszeichen im Regex-String maskiert werden, außerdem muss auch ein 
   * Backslash am Ende des Regex-Strings geschützt werden (er würde sonst das Begrenzungs-
   * zeichen am Ende maskieren).
   *
   * Wir können nicht blindlings alle Begrenzungszeichen maskieren, weil damit die bereits
   * maskierten Zeichen die Regex ungültig machen würden. Bei einer Regex wie '\/' würde
   * blindes Maskieren '\\/' ergeben, was mit den Begrenzungszeichen zu einem ungültigen
   * Pattern-Argument führt: '/\\//'.
   *
   * Wir unterteilen die Regex deshalb in Abschnitte: bereits maskierte Zeichen, nicht maskierte
   * Schrägstriche (die wir maskieren müssen) und alles andere. Ein Backslash am Ende muss 
   * als Spezialfall gesondert behandelt und ebenfalls maskiert werden.
   */
  if (! preg_match('{\\\\(?:/|$)}', $nackte_regex)) /* '/', gefolgt von '\' oder EOS */
  {
     /* Weder bereits maskierte Zeichen noch ein Backslash am Ende -- wir können die
      * Schrägstriche blindlings maskieren. * /
     $maskiert = preg_replace('!/!', '\/', $nackte_regex);
  }
  else
  {
     /* Mit diesem Pattern unterteilen wir den Regex-String $nackte_regex.
      * In den einfangenden Klammern die zwei Teile, deren Treffer wir maskieren werden. */
     $pattern = '{  [^\\\\/]+  |  \\\\.  |  (  /  |  \\\\$  )  }sx';
     /* Unsere Callback-Funktion wird bei jedem Treffer von $pattern im String $nackte_regex
      * aufgerufen. Wenn $treffer[1] nicht leer ist, geben wir die maskierte Version davon zurück,
      * sonst einfach den unbehandelten Treffer. */
     $f = create_function('$treffer', '           // Dieser lange
          if (empty($treffer[1]))                 // String in Hochkommas
              return $treffer[0];                 // wird zu
          else                                    // unserer
              return "\\\\" . $treffer[1];        // Callback-Funktion.
     ');
     /* Nun endlich $pattern auf $nackte_regex ansetzen. */
     $maskiert = preg_replace_callback($pattern, $f, $nackte_regex);
  }
  /* $maskiert kann jetzt gefahrlos in Begrenzungszeichen eingefasst werden. */
  return "/$maskiert/$modifikatoren";
}

This algorithm is complex enough that I certainly do not want to reimplement it every time I need it. I therefore encapsulated it in a function, and it would be nice if that function became part of the preg package.

It is instructive to analyze the regex near the end of the function and how it cooperates with preg_replace_callback and the callback to escape only slashes that are not already escaped.

  

 

 

 

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