Use No-capture Modifier with Regex Functions in PHP 8.2

Use No-capture Modifier with Regex Functions in PHP 8.2

PHP supports various regular expression modifiers that can be used with preg_* functions (e.g. preg_match). For example, the i modifier can be used for case-insensitive match. Since PHP 8.2, we can use the n modifier, which do not capture non-named groups.

Consider an example of regular expression that extracts weight measurements (e.g. 2 kg, 5 lb) from the text:

<?php

preg_match('/\d+ (g|kg|oz|lb)/', 'Package weight is 5 lb', $matches);
var_dump($matches);

Output:

array(2) {
  [0]=> string(4) "5 lb"
  [1]=> string(2) "lb"
}

Regular expression has one capturing group for the measurement units. Capturing group can be ignored in the result by using n modifier:

<?php

preg_match('/\d+ (g|kg|oz|lb)/n', 'Package weight is 5 lb', $matches);
var_dump($matches);

Output:

array(1) {
  [0]=> string(4) "5 lb"
}

Leave a Comment

Cancel reply

Your email address will not be published.