拆分方括号内的每个字符

I have a problem with a regex, I have the following string

[date|Y-m-d]

which is a Token extracted from a text and I need to extract 'date' and 'Y-m-d', but I haven't been able to achieve my goal with the following regex, can someone help me

(?:\[)([^\|]+)(?:\])

The tokens can be like:

[date|Y-m-d] \\ should extract 'date' and 'Y-m-d'
[date|Y-m-d|today] \\ should extract 'date', 'Y-m-d' and 'today'

Use a regex pattern

(?<=^\[|\|)[^|\[\]]*(?=\||\]$)

Test this regex solution here and a related PHP code here.

I assume you may have strings containing those substrings inside brackets and you want to extract them.

You may use

$str = '[date|Y-m-d] [date|Y-m-d|today]';
preg_match_all('/\[([^][]+)]/', $str, $matches);
$res = [];
foreach ($matches[1] as $m) {
    array_push($res,explode("|", $m));
}
print_r($res);

See the PHP demo

Also, see the identical solution for scenarios where only 1 match per string is expected (PHP demo):

$str = 'A single match example [date|Y-m-d|today] here.';
if (preg_match('/\[([^][]+)]/', $str, $matches)) {
    print_r(explode("|", $matches[1]));
}

Details

  • The '/\[([^][]+)]/' pattern extracts all texts between square brackets containing no [ and ] in it (capturing the part without the leading/trailing brackets into Group 1)
  • Then an array is built by exploding each match with |.

If you just have a string equal to [...|...|...|etc.] you may either use Shivrudra's approach, or a very simple preg_match_all:

$str = '[date|Y-m-d]';
preg_match_all('/[^][|]+/', $str, $matches);
print_r($matches[0]);

See another PHP demo.

The [^][|]+ pattern matches 1 or more chars other than [, ] and |. See the regex demo.

You can also achieve this by removing bracket with ltrim() & rtrim(). Then you can use explode with ":".

$str = explode(':', ltrim( rtrim($str, ']'), '['));
print_r( $str );

Output:

Array
(
    [0] => date
    [1] => Y-m-d
)