Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.