XML technologies / Regular expressions / PHP / “Missing” preg functions / Checking a pattern argument’s syntax
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Even after correctly escaping the regex string and enclosing it in delimiters, we still do not know whether the original regex is syntactically valid.
For example, the regex string might be ‘*.txt’ because someone entered a file wildcard instead of a regex. The result of preg_regex_to_pattern is /*.txt/, but that is not a valid regular expression and produces the following error message if PHP warnings are enabled:
Compilation failed: nothing to repeat at offset 0PHP provides no function for checking regex syntax, so I wrote one.
Function preg_pattern_error checks the pattern argument by trying it, on the highlighted line with preg_match in the middle. The rest of the function catches any PHP error messages that may be generated.
/*
* preg_pattern_error gibt bei einem ungültigen Pattern-Argument oder einer syntaktisch
* ungültigen Regex eine Fehlermeldung zurück. Im anderen Fall (wohlgeformtes Pattern-
* Argument und Regex) wird false zurückgegeben.
*/
function preg_pattern_error($pattern)
{
/*
* Wir überprüfen das Pattern einfach dadurch, indem wir es ausprobieren.
* Das Erkennen und Abfangen einer Fehlermeldung ist nicht so einfach, besonders, weil wir
* natürlich keine globalen Einstellungen (z.B. den Wert von $php_errormsg) verändern wollen.
* Wenn 'track_errors' aktiviert ist, speichern wir den Wert von $php_errormsg ab und
* holen ihn nachher zurück. Wenn die Option 'track_errors' nicht gesetzt ist, setzen
* wir sie (weil wir diese Option benötigen) und schalten sie am Ende wieder aus.
*/
if ($old_track = ini_get("track_errors"))
$old_message = isset($php_errormsg) ? $php_errormsg : false;
else
ini_set('track_errors', 1);
/* Die Option 'track_errors' ist jetzt sicher eingeschaltet. */
unset($php_errormsg);
@ preg_match($pattern, ""); /* Ausprobieren! */
$return_value = isset($php_errormsg) ? $php_errormsg : false;
/* Fehlermeldung abgefangen und gespeichert -- vorherigen Zustand wiederherstellen. */
if ($old_track)
$php_errormsg = isset($old_message) ? $old_message : false;
else
ini_set('track_errors', 0);
return $return_value;
}
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