Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex not working as expected

Tags:

regex

php

I have the path of a file and I want to extract parts of it with a regex. But the pattern seems to be wrong, it only gives me the last match.

$s = 'engine/plugins/renderer_smarty/plugins/css_minify/';
preg_match('@^engine/(plugins/(.+?)/)+$@i',$s,$matches);

Result:

array (3):
    0 => string (50): "engine/plugins/renderer_smarty/plugins/css_minify/"
    1 => string (19): "plugins/css_minify/"
    2 => string (10): "css_minify"

Expected result:

array (5):
    0 => string (50): "engine/plugins/renderer_smarty/plugins/css_minify/"
    1 => string (24): "plugins/renderer_smarty/"
    2 => string (15): "renderer_smarty"
    3 => string (19): "plugins/css_minify/"
    4 => string (10): "css_minify"

What's wrong in the pattern?

Thanks!

like image 387
Volker Heiselmayer Avatar asked Mar 13 '26 12:03

Volker Heiselmayer


1 Answers

You may use

preg_match_all('@(?<=/)plugins/([^/]+)@i',$s,$matches);

to match all the substrings you need.

See this PHP demo and a regex demo. The issue you are facing is a by design regex repeated capturing group behavior, only the values captured with the last iteration are stored in the group memory buffer.

Pattern details:

  • (?<=/) - a positive lookbehind check if there is a / on the left, if yes,proceed matching...
  • plugins/ - a literal plugins/ substring
  • ([^/]+) - Group 1: one or more (due to + quantifier) chars other than / (the [^/] is a negated character class matching any char but the one(s) defined in the class.
like image 90
Wiktor Stribiżew Avatar answered Mar 16 '26 02:03

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!