How can I get preg_match_all to match angle brackets?

可紊 提交于 2021-01-28 15:37:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!