← All writing

Treat a regex error differently from no match

PHP 8.3+Sources checked 2026-09-13

A configurable import rule uses a regular expression. A malformed pattern is reported as “no matching rows,” so an operator assumes the supplier sent an empty file. The parser hid an execution error inside a normal negative result.

Inspect all three outcomes

<?php
$matched = preg_match('/^SKU-[0-9]+$/D', 'SKU-42');
$missing = preg_match('/^SKU-[0-9]+$/D', 'other');
assert($matched === 1);
assert($missing === 0);

preg_match returns 1 for a match, 0 for no match, and false for an error. In application code, check === false first and report a configuration or processing failure. preg_last_error_msg() can help diagnose the PCRE error without presenting raw internals to an end user.

Keep patterns bounded

If a user supplies a literal search term, quote it with preg_quote before embedding it in a pattern, including the delimiter argument. Do not treat arbitrary user text as an intentional regex unless that is a clearly supported feature.

Even syntactically valid patterns can be expensive against particular inputs. Apply sensible input-size limits and avoid unnecessarily ambiguous repetition. An import timeout should leave a visible failed job or rejected file rather than a partial success message.

Test a matching code, a nonmatching code, and a deliberately invalid configured pattern through your error-handling path. Also test the maximum accepted input length. A single happy-path regex assertion does not verify that a batch importer survives a bad pattern or preserves its existing records after failure.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.