Destramic Posted July 25, 2015 Share Posted July 25, 2015 hey guys i'm having a slight problem with getting the correct match, which i know is down to my regex pattern. with my first result i get [/name/hello[/second] but im after the result of [/name/hello[/second]] with the closing bracket at the end. is it possible for me to match that? $pattern = "hello[/name/hello[/second][/bye]"; if (preg_match_all('/\[(.*?)\]/', $pattern, $matches)) { print_r($matches) } Array ( [0] => Array ( [0] => [/name/hello[/second] // --- > [/name/hello[/second]] [1] => [/bye] ) [1] => Array ( [0] => /name/hello[/second [1] => /bye ) ) thank you Quote Link to comment https://forums.phpfreaks.com/topic/297475-matching-pattern/ Share on other sites More sharing options...
requinix Posted July 25, 2015 Share Posted July 25, 2015 .*? will stop as soon as possible, and according to your regex that means as soon as it finds a closing ]. The problem of dealing with matching parentheses, or matching brackets, needs to be done using recursion. Your pattern is very simple, fortunately, so it's easy to add recursion in: '/\[((?:[^\[\]]*|(?R))*)\]/'1. The [^\[\]]* matches anything that doesn't look like the pattern delimiters. Your pattern only uses [ and ] so that's all you have to check for. This repeats by itself for optimization. 2. The (?R) does recursion using the entire pattern (it's possible to recurse only a portion of it). Remember to repeat the two together. Note that the input string you gave does not have balanced []s so you need to fix that or else the pattern will not match anything. http://3v4l.org/vruf4 Quote Link to comment https://forums.phpfreaks.com/topic/297475-matching-pattern/#findComment-1517390 Share on other sites More sharing options...
Destramic Posted July 26, 2015 Author Share Posted July 26, 2015 works like a dream even works if i put parameters in like so <?php $pattern = "hello[/name/hello[/s:second*]][/bye]"; or $pattern = "hello[/name/hello[/s:second]][/bye]"; or $pattern = "hello[/name/hello[/:second(1|2)]][/bye]"; thank you...you've been a great help Quote Link to comment https://forums.phpfreaks.com/topic/297475-matching-pattern/#findComment-1517426 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.