Jump to content

matching pattern


Destramic

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/297475-matching-pattern/
Share on other sites

.*? 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

Link to comment
https://forums.phpfreaks.com/topic/297475-matching-pattern/#findComment-1517390
Share on other sites

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

Link to comment
https://forums.phpfreaks.com/topic/297475-matching-pattern/#findComment-1517426
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.