greenbandit
greenbandit

Reputation: 2275

How to catch text inside brackets

I have this little code to capture text between brackets:

$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place]';    
preg_match_all('/\[([^\]]*)\]/', $string, $matches);
print_($matches[0]);

What I get is the following:

    Array(
      [0] => [title=my title]
      [1] => [maps:some cool place]
    )

I want to make more restrictive to avoid "[some-not cool]" or "[another+stuff]", so I need to catch only [some:thing] and [some=thing].

How can I do it?

Upvotes: 1

Views: 211

Answers (2)

avpaderno
avpaderno

Reputation: 29669

If the part before the colons or the equal should be made only of letters, you can use the following code:

preg_match_all('/\[([a-z]+[:=][^\]]+)\]/i', $string, $matches);

If the first part is something more similar to a PHP identifier (except for the $), then you can use the following code:

preg_match_all('/\[([a-z_]+[a-z0-9_]+[:=][^\]]+)\]/i', $string, $matches);

Upvotes: 1

Godwin
Godwin

Reputation: 9907

This will catch everything that contains a '=' or ':' and ignore others:

$string = '[title=my title] http://bit.ly/gANFxi [maps:some cool place] [some-not cool] or [another+stuff]';
preg_match_all('/\\[([^\\]]*[\\=|\\:][^\\]]*)\\]/', $string, $matches);
print_r($matches[0]);

Does this do the trick? Or are there further requirements? That is, this return "[some stuff=some:thing]" but should it? (note both the multiple words and both '=' and ':').

Upvotes: 2

Related Questions