user2103849
user2103849

Reputation: 551

How to get content between the brackets using regex

I have a string like so:

[abc] 12345 [abc] 67890 [/abc] [/abc]

I would like to match the content inside the brackets but NOT return a match if another opening bracket is found (e.g., [abc]). The function /\[abc\](.*)\[\/abc\]/i would output:

12345 [abc] 67890 [/abc]

But that's not what i want, because there's another opening bracket inside the text. The expected result would be:

67890

Any suggestions on how to solve it?

Upvotes: 2

Views: 158

Answers (4)

NeverHopeless
NeverHopeless

Reputation: 11233

Check this pattern:

(\d+)(?:\s*\[/abc\]\s*)+$

It will look from the right side and skip all ending tags like [/abc] and pick the very next number.

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

Nothing new, but a shorter write:

$subject = '[abc] 12345 [abc] 67890 [/abc] [/abc]';
$pattern = '~\[abc]\K[^[]++(?=\[/abc])~i';
preg_match($pattern, $subject, $result);

Upvotes: 0

Civa
Civa

Reputation: 2176

Try this pattern:

\[[^\/\]]*\]([^\[]*)\[\/[^\]]*\]

\[ ---> character [

[^\/\]]* ---> read data till it reaches ] or /

\] ---> character ]

[^\[]* ---> read data till character [ reached

() ---> indicates group to we can select that group as \1

Demo http://rubular.com/r/shwsqTE61R

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Yes, just state that you don't want to allow brackets between your tags by using [^\[\]]* instead of .* (which would match anything, including brackets):

/\[abc\]([^\[\]]*)\[\/abc\]/i

Upvotes: 3

Related Questions