问题
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?
回答1:
You're missing correct delimiters (your < >
are considered as delimiters in this case)
$pattern = '~<\[.+?\]>~';
回答2:
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]>
)
)
来源:https://stackoverflow.com/questions/8273922/how-can-i-get-preg-match-all-to-match-angle-brackets