stackdave
stackdave

Reputation: 7094

php regex - get content with square brackets escaped inside square brackets

this is some hard, I have solutions for this with srtpos, but it's ugly, I need help to do it with preg_pos or preg_match . I have a string like below:

$text="Some 
[parameter=value\[anoter value|subparam=20] with  or 
[parameter|value\]anoter value|subparam=21|nothing] or 
[parameter=value\[anoter value\]|subparam=22] ";

... I would like to get the following result:

array (
  0 => '=value[anoter value|subparam=20',
  1 => '|value[anoter value|subparam=21|nothing',
  2 => '=value[anoter value]|subparam=22',
)

I mean i know my parameter: [parameter---get this section---] after 'parameter' all text can be to change, and it can contains escaped: bracket - square bracket - parenthesis - ampersand. thanks !

Upvotes: 1

Views: 445

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

Even if you extract the substrings you are interested by, you will need to remove the escaped square brackets in a second time. Let's see the full solution:

$pattern = '~\[\w+\K[^]\\\]*(?:(?:\\\.)+[^]\\\]*)*+(?=])~s';

if (preg_match_all($pattern, $str, $m))
    $result = array_map(function ($item) {
        return strtr($item, array('\]' => ']', '\[' => '['));
    }, $m[0]);

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174874

Use \K to discard the previously matched characters.

\[parameter\K(?:\\[\]\[]|[^\[\]])*

DEMO

$re = "~\\[parameter\\K(?:\\\\[\\]\\[]|[^\\[\\]])*~m";
$str = "Some \n[parameter=value\[anoter value|subparam=20] with or \n[parameter|value\]anoter value|subparam=21|nothing] or \n[parameter=value\[anoter value\]|subparam=22] \";\nfoo bar";
preg_match_all($re, $str, $matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => =value\[anoter value|subparam=20
            [1] => |value\]anoter value|subparam=21|nothing
            [2] => =value\[anoter value\]|subparam=22
        )

)

Upvotes: 0

Related Questions