<?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);
- Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array(3) {
[0]=>
array(2) {
[0]=>
string(5) "[baz]"
[1]=>
string(3) "baz"
}
[1]=>
array(10) {
[0]=>
string(41) "[you|him|her|foo|bar|baz|foo|option|test]"
[1]=>
string(3) "you"
[2]=>
string(3) "him"
[3]=>
string(3) "her"
[4]=>
string(3) "foo"
[5]=>
string(3) "bar"
[6]=>
string(3) "baz"
[7]=>
string(3) "foo"
[8]=>
string(6) "option"
[9]=>
string(4) "test"
}
[2]=>
array(2) {
[0]=>
string(9) "[another]"
[1]=>
string(7) "another"
}
}
- Output for 5.6.0 - 5.6.25
- Parse error: syntax error, unexpected '(' in /in/isnnT on line 11
Process exited with code 255.
preferences:
137.66 ms | 407 KiB | 5 Q