[英]PREG_MATCH_ALL taking the last match
hello im just having a problem here with PREG_MATCH_ALL() lets say i have 2 strings ... Save You and What If Uploader Name i need to retreive Save You so i'm using the folowing paterns 你好我刚刚在这里遇到问题PREG_MATCH_ALL()让我说我有2个字符串...保存你和如果上传者姓名我需要撤回保存你所以我正在使用下面的模式
preg_match_all('/<span id="title.*">(.*)<\/span>/i',,);
as a result i get 结果我得到了
Save You Uploader Name
保存您的上传者名称
I think this is because it's taking the last any way to fix it ? 我认为这是因为它采取了最后一种方法来解决它? or like matching the first ?
或者喜欢匹配第一个? thank you
谢谢
EDIT: 编辑:
<a href="#" onclick="searchActions.showLyrics('14840_100733666_21',9965243); return false;">Can't Keep My Hands Off You</a></span>
get as result 得到的结果
<a href="Your Love Is A Lie"</a>
with 同
/<span id="title(.*?)">(.*?)<\/span>/i
The reason is that .*
is greedy. 原因是
.*
贪婪。 The first .*
(right after title
) will swallow as many characters as it can, and then backtrack from the end of the string until the rest of the regexp can match. 第一个
.*
( title
后面)会吞下尽可能多的字符,然后从字符串的末尾开始回溯,直到正则表达式的其余部分匹配为止。
To fix it, either use the ungreedy version .*?
要修复它,要么使用ungreedy版本
.*?
, and/or replace the .
,和/或更换
.
with some character class that can't match a quote (such as [^"]
): 一些与引号不匹配的字符类(例如
[^"]
):
preg_match_all('/<span id="title[^"]*">(.*?)<\/span>/i', ..., ...);
For more information, see http://www.php.net/manual/en/regexp.reference.repetition.php 有关更多信息,请参阅http://www.php.net/manual/en/regexp.reference.repetition.php
(Ps. Levi Morrison is right — this is not a good way to parse HTML. Use a real HTML parser, such as DOMDocument::loadHTML()
.) (Ps.Levi Morrison是对的 - 这不是解析HTML的好方法。使用真正的HTML解析器,例如
DOMDocument::loadHTML()
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.