0
$content = "[2][6][11]";

This i would like to split into an array with values [2], [6] and [11].

preg_split("/\[*\]/i", $content);

Wrong output: Array ( [0] => [2 [1] => [5 [2] => )

Any help what's wrong on the regular expression.

thanks.

5
  • preg_split("/\h*[][]/", $content, -1, PREG_SPLIT_NO_EMPTY) Commented Jan 20, 2017 at 15:40
  • 1
    If it's guaranteed to be a number between the braces, this regex pattern will work: /(\[\d+\])/. Commented Jan 20, 2017 at 15:42
  • assuming there are only numbers in the braces: preg_split("/(\[[0-9]+\])/", $content); Commented Jan 20, 2017 at 15:46
  • 1
    @ThomasD. That won't work because you're not escaping the square brackets. Commented Jan 20, 2017 at 15:47
  • @jhmckimm thanks for the tip. forgot to format as code, thats why they didn't show ;) Commented Jan 20, 2017 at 15:50

3 Answers 3

1

You can use lookarounds for this split:

$content = "[2][6][11]";
print_r(preg_split('/(?<=\])(?=\[)/', $content));

Output:

Array
(
    [0] => [2]
    [1] => [6]
    [2] => [11]
)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use lookarounds to test what are the characters around the position you want to find without matching them.

print_r(preg_split('~(?<=])(?=\[)~', $content));

Note that if you already know how your string is formatted, you can also use preg_match_all with a more simple pattern: ~\[\d+]~

Comments

0

You can also do it with preg_match_all :

$content = "[2][6][11]";
preg_match_all("/\[.*\]/Ui", $content, $matches);
$result = $matches[0];
print_r($result);

Output:

Array
(
    [0] => [2]
    [1] => [6]
    [2] => [11]
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.