Reputation: 7094
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
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
Reputation: 174874
Use \K
to discard the previously matched characters.
\[parameter\K(?:\\[\]\[]|[^\[\]])*
$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