Emil D
Emil D

Reputation: 1904

How can I get preg_match_all to match angle brackets?

I know it's probably a dumb question, but I am stuck trying to figure out how to make preg_match_all to do what I want...

I want to match strings that look like <[someText]> Also, I would like to do this in a lazy fashion, so if a have a string like

$myString = '<[someText]> blah blah blah <[someOtherText]> lala [doNotMatchThis] ';

I would like to have 2 matches: '<[someText]>' and '<[someOtherText]>' as opposed to a single match '<[someText]> blah blah blah <[someOtherText]>'

I am trying to match this with the following pattern

$pattern = '<\[.+?\]>';

but for some reason, I'm getting 3 matches: [someText], [someOtherText] and [doNotMatchThis]

This leads me to believe that for some reason the angle brackets are interfering, which I find strange because they are not supposed to be metacharacters.

What am I doing wrong?

Upvotes: 1

Views: 1312

Answers (2)

Martin.
Martin.

Reputation: 10539

You're missing correct delimiters (your < > are considered as delimiters in this case)

$pattern = '~<\[.+?\]>~';

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170227

Your pattern needs delimiters (now the < and > are "seen" as delimiters).

Try this:

$pattern = '/<\[.+?\]>/';

The following:

$myString = '<[someText]> blah blah blah <[someOtherText]> lala [doNotMatchThis] ';
$pattern = '/<\[.+?\]>/';
preg_match_all($pattern, $myString, $matches);
print_r($matches);

will print:

Array
(
    [0] => Array
        (
            [0] => <[someText]>
            [1] => <[someOtherText]>
        )

)

Upvotes: 3

Related Questions