preg_match_all doesn't match when using a carat (^)

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-21 13:56:32

问题


I'm using preg_match_all to find a URL in a HTML file. The URL always appears at the start of the line, with no leading space, like this:

<A HREF="/link/to/here"><strong>Next</strong></A>

I used this to match it:

preg_match_all('|^<A HREF="(?<url>.*?)"><strong>Next</strong>|', $html, $url_matches);

It didn't work until I removed the carat (^) character. I thought that the carat matched the start of a line. Why is it causing my match to fail?


回答1:


You have to add the m modifier:

preg_match_all('|^<A HREF="(?<url>.*?)"><strong>Next</strong>|m', $html, $url_matches);

then ^ matches at start of a line, else it would only match at the start of the entire string.

More Info: http://php.net/manual/en/reference.pcre.pattern.modifiers.php




回答2:


^ matches start-of-string not start-of-line. Use the m ("multi-line") modifier: //m



来源:https://stackoverflow.com/questions/6179991/preg-match-all-doesnt-match-when-using-a-carat

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