37: Migrate mbstring Regular Expressions to PCRE
Overview
Section titled “Overview”Replace a multibyte match and split with preg_match() and preg_split(). PHP 8.6 deprecates the mbstring regex functions backed by Oniguruma.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable mbregex-to-pcre.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/37-mbregex-to-pcre/mbregex-to-pcre.php<?php
declare(strict_types=1);
$text = "Montréal; Αθήνα, Cafe\u{0301}";$tokens = preg_split('/[;,]\s*/u', $text);if ($tokens === false) { throw new RuntimeException(preg_last_error_msg());}
foreach ($tokens as $token) { $result = preg_match('/^\p{L}[\p{L}\p{M}]*$/u', $token); if ($result === false) { throw new RuntimeException(preg_last_error_msg()); } echo $token, $result === 1 ? " OK\n" : " invalid\n";}Expected Result
Section titled “Expected Result”Montréal OKΑθήνα OKCafé OKWhy It Works
Section titled “Why It Works”PCRE’s u modifier interprets the subject and pattern as UTF-8. \p{L} matches Unicode letters and \p{M} matches combining marks. Check the pattern syntax, captured groups, and error handling during migration because PCRE and mbregex have different APIs.
Exercise
Section titled “Exercise”Add an input with an ASCII digit and one with a decomposed accent. The digit-containing token should fail the letter test while the decomposed token should pass.
Wrap-up
Section titled “Wrap-up”Continue with Replace Deprecated Numeric Aliases.