Skip to content

Add a strict ICU to PCRE translator for REGEXP functions - #640

Draft
JanJakes wants to merge 5 commits into
trunkfrom
regexp-icu-translator
Draft

JanJakes wants to merge 5 commits into
trunkfrom
regexp-icu-translator

Conversation

@JanJakes

@JanJakes JanJakes commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

MySQL reads REGEXP patterns with ICU, and the driver runs them with PHP's PCRE. This PR adds a strict translator between the two: a pattern either gets a correct PCRE translation, or it raises an error. Nothing reaches PCRE unchecked.

This is an alternative to #629. Both PRs translate ICU syntax to PCRE. They differ in what happens to syntax that has no translation: #629 passes it to PCRE, and this PR rejects it.

The translation lives in a new internal class, WP_ICU_Regex_Translator. One regex splits a pattern into tokens. Each token either means the same in PCRE, or it has a translation.

These are the changes for queries:

  • Unsupported syntax is an error that names the syntax, like Unsupported regular expression syntax: (?x, with MySQL's error number 3690. This covers PCRE-only syntax, like (?R) or (*ACCEPT), and the ICU syntax that is left out, like nested sets, set operations, and the flag x.
  • Line ends are translated for ., ^, $, \Z, and \R, instead of using PCRE's (*ANY) setting. This fixes [^a-z]cat, which didn't match dog\r\ncat.
  • Classes match like in ICU with every PCRE version: \w, \b, the POSIX classes, and [:upper:] and [:lower:] when ignoring case.
  • Code point escapes \uhhhh, \Uhhhhhhhh, \0ooo, and \cX match their characters.
  • An escaped letter without a meaning is the letter, like in MySQL. So \y matches y, and \K matches K and is never PCRE's \K.
  • A PCRE bug is avoided. On PHP 7.3 to 8.1, [^s] could match a part of a character when ignoring case.
  • Older MySQL syntax keeps working: the word boundaries [[:<:]] and [[:>:]], and a literal {. MySQL 8 rejects them, but MySQL 5.7 and MariaDB accept them, and existing queries use them.
  • Regex errors look like in PDO MySQL. They carry MySQL's error number, like SQLSTATE[HY000]: General error: 3685 Illegal argument to a regular expression. for an empty pattern.

The test suites now know what is unsupported. A new unsupported.json lists 826 cases that must raise error 3690, so they can't return a wrong result. The known failures of each function drop from about 900 to about 60 to 80, each with its cause.

Why

For a query, a wrong result without an error is the worst outcome. The goal of this PR is to never return one for syntax that isn't supported, and to behave the same with every PCRE version.

This table compares the 16,649 MySQL-judged cases of the REGEXP suites, on PHP 8.5:

Outcome trunk #629 This PR
Wrong result without an error 145 61 47
A value where MySQL raises an error 14 8 0
An error where MySQL returns a value 584 182 790

So #629 supports more syntax, and this PR returns fewer wrong results. Most of the 47 wrong results are case folding, like ß with ss.

Two more comparisons:

Trade-offs

This is what the strict approach costs:

  • Less syntax is supported. Some patterns that work in MySQL, and in Translate more of ICU's regex syntax for REGEXP functions #629, are errors here. These are the 790 cases in the table.
  • Some patterns that worked before are errors now, like (?x)a b with the flag x, and a comment with a backslash, like (?#\G).
  • Long lists of words with boundaries can fail. \b and [[:<:]] expand to ICU's word class. A pattern with more than about 420 alternatives like \bword\b, or about 220 like [[:<:]]word[[:>:]], is too large for PCRE, and raises an error. On trunk, the limits are about 4,000 and 1,800.
  • A few results still differ from MySQL. The class comment of WP_ICU_Regex_Translator lists these differences.
  • The code doesn't get smaller. It is about as much code as Translate more of ICU's regex syntax for REGEXP functions #629.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@JanJakes
JanJakes force-pushed the regexp-icu-translator branch 6 times, most recently from 60b184e to 32438c3 Compare November 25, 2026 14:45
MySQL reads REGEXP patterns with ICU, and the driver runs them with
PCRE. The two differ in sets, escapes, line ends, word characters,
and POSIX classes.

WP_ICU_Regex_Translator splits a pattern into tokens with one regex.
A token either means the same in PCRE, or it has a translation. Any
other text is rejected, so PCRE-only syntax, like "(?R)" or "\K", and
ICU syntax that isn't supported, like set operations or the "x" flag,
never reach PCRE.

The REGEXP functions don't use the class yet.
When ignoring case, PCRE 10.32 to 10.39 with JIT can match only a part
of a character with a negated set of one character whose letter has more
than one other case, like "[^s]". On "日", it matched two of the three
bytes, so REGEXP_SUBSTR() or REGEXP_REPLACE() could return invalid
UTF-8. PHP 7.3 to 8.1 bundle these versions.

Repeat the character in such a set. PCRE then compiles a class, which
doesn't have the bug.
The REGEXP functions need more from the translator than a text pattern:

- Match bytes, for binary strings. Classes and word boundaries are the
  ones of PCRE, and a line ends at LF, VT, FF, and CR, like in MySQL.
- Accept a look-behind only when it holds characters, sets, and "|".
  Older PCRE versions reject other look-behinds, so the same patterns
  now work with every version.
- Raise WP_ICU_Regex_Exception with the MySQL error number 3690, and
  name the rejected syntax in the message, like "(?x" or "\10".
- Write a NUL byte after a backslash as "\x00". PHP before 8.2 rejects
  a NUL byte in a pattern.
MySQL uses ICU for regular expressions, and the REGEXP functions passed
a pattern to PCRE almost as it was. PCRE reads some of the syntax in
another way, so a query could return a wrong result without an error.

The functions now use WP_ICU_Regex_Translator. A pattern either gets a
correct translation, or it raises an error that names its syntax. This
replaces the pattern escaping and the "(*ANY)" line end setting, and
fixes these results:

- "[^a-z]cat" didn't match "dog\r\ncat".
- "[^s]" matched a part of a character on PHP 7.3 to 8.1.
- A code point escape, "\w" with marks, and the POSIX classes now work
  like in ICU.

Regular expression errors now carry their MySQL error number, like 3685
for an empty pattern and 3690 for syntax that isn't supported.

In the REGEXP suites, "unsupported.json" lists the cases with syntax
that isn't supported. They must raise error 3690, so they can't return
a wrong result. The known failures of each function shrink to about 60
cases, each with its cause, and they depend on the PCRE version in
three places only.
A "\b" becomes a condition with three word classes, because PCRE has other
word characters than ICU. Next to a literal ASCII letter, digit, or "_" that
is not repeated, one side of the boundary is known, so one class is enough:
"\bword\b" is now "(?<![…])word(?![…])". The same holds for "\B".

Measured on PHP 8.5 with PCRE 10.49, on 5.9 MB of text that does not match:

- "\bneedle\b|\bhaystack\b|\bthread\b" takes 7.9 ms, and 54.7 ms before. Without
  JIT, it takes 40.7 ms, and 685 ms before.
- "\bneedle\b" takes 1.7 ms, and 3.1 ms before.
- A list of "\bword\b" alternatives compiles with up to 426 words, and with up
  to 148 before.

A boundary next to a group, a set, or a repeated character is unchanged.
@JanJakes
JanJakes force-pushed the regexp-icu-translator branch from 32438c3 to 57a4b7a Compare November 25, 2026 15:20

@JanJakes JanJakes left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some comments are not clear. Also, why is the new code not using PHP return type hints?

*
* @internal
*/
class WP_ICU_Regex_Exception extends DomainException {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is DomainException the right choice here?

* repetitions such as (?<=a{2}).
* - Flags x and w, named characters (\N{name}), backreferences above \9,
* quantified anchors, empty \Q\E, and comments containing a backslash
* or followed by a quantifier.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't some of these be separate bullet points? Does it make sense to keep them in one?

* @internal
*/
class WP_ICU_Regex_Translator {
// In byte mode, 0x85 is data. Exclude it when translating ICU line endings.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the comment explain a bit more generally what this does?

'\V' => '[^\n\x0B\f\r]',
);

// PCRE counts "²" as a word character. ICU excludes it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds like all of this is just for the "²" character. It suspect it isn't.

);

// Translations for ".", "^", and "$" under the active flags. The ".*" entries
// restrict a leading ".*" or ".+" to the search offset (\G) or a new line.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are "the active flags"?

private $groups = array();

/**
* Deferred start checks in NUL placeholder order.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is not very clear.

private $has_backreference = false;

/**
* Whether a leading .* or .+ can restrict the match start here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does "here" means in this case?

private $is_after_word = false;

/**
* Whether \G in the input pattern must fail.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And why?

*
* @var bool
*/
private $bytes;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a good property name? Sounds like it should contain some bytes.

* @param bool $bytes Match individual bytes using PCRE's byte-mode classes and boundaries.
*
* @throws WP_ICU_Regex_Exception On unsupported syntax, flags, or a translation limit.
* @return string A pattern for the preg_*() functions. It can still fail to compile.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does WP use @throws annotations? In any case, put them under @return.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant