- substr_count: documentation ( source)
- var_dump: documentation ( source)
- preg_match_all: documentation ( source)
- implode: documentation ( source)
<?php
$string = "some text here [baz] and here [you|him|her|foo|bar|baz|foo|option|test] and even here [another].";
$pattern = (function () use ($string) {
$array = [];
for ($i = 0; $i <= substr_count($string, "|"); $i++) {
$array[] = $i == 0 ? '([^][|]+)' : '([^][|]+)?';
}
return implode("\|?", $array);
})();
preg_match_all("~\[$pattern]~", $string, $matches, PREG_SET_ORDER);
var_dump($matches);