Gomer
Gomer

Reputation: 169

Match all square brackets with preg_match_all`

I'm trying to match multiple square bracket tags in a string to extract them from the string.

For example:

$string = 'Request: [CODE]sksdjdiwjwdwdkw[/CODE] Response: [CODE]sksdjdiwjwdwdkw[/CODE]';

preg_match_all('/\[CODE\](.*)\[\/CODE\]/',$string) matches everything between the first [CODE] and last [/CODE].

Does anyone have a idea on how the expression are suppost to look like?

Upvotes: 1

Views: 2574

Answers (2)

Cfreak
Cfreak

Reputation: 19319

Don't use .* (faster than non-greedy)

preg_match_all('/\[CODE\]([^\[]+)\[\/CODE\]/',$string);

Upvotes: 1

codaddict
codaddict

Reputation: 455440

Try making your match non-greedy:

preg_match_all('/\[CODE\](.*?)\[\/CODE\]/',$string)
                          ^^^

Upvotes: 3

Related Questions