3

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!

2
  • 1
    What about just preg_match_all('@(?<=/)plugins/([^/]+)@i',$s,$matches);? See this 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. Commented Nov 17, 2016 at 8:08
  • Thanks a lot, that's the solution! I didn't know that only the last iteration is stored. Commented Nov 17, 2016 at 8:44

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.