[英]How to get the value of groups in preg_match_all php?
Hi, My pattern is: 嗨,我的模式是:
'<span\s+id="bodyHolder_newstextDetail_nwstxtPicPane"><a\s+href="(.*)"\s+target="_blank"><img\s+alt="(.*)"\s+title="(.*)"\s+src=\'(.*)\'\s+/>'
And the string: 和字符串:
<div class="nwstxtpic">
<span id="bodyHolder_newstextDetail_nwstxtPicPane"><a href="xxxxx" target="_blank"><img alt="xxxxx" title="xxxxx" src='xxxxx' />
Well, my php code for finding and getting the value of 4 groups that i have defined in patern is: 好吧,我用于查找和获取我在patern中定义的4个组的值的php代码是:
$picinfo=preg_match_all('/<span\s+id="bodyHolder_newstextDetail_nwstxtPicPane"><a\s+href="(.*)"\s+target="_blank"><img\s+alt="(.*)"\s+title="(.*)"\s+src=\'(.*)\'\s+/>/',$newscontent,$matches);
foreach ($matches[0] as $match) {
echo $match;
}
I dont know how to get the value of these 4 groups 我不知道如何获得这4组的价值
href="(.*)"
alt="(.*)"
title="(.*)"
src=\'(.*)\'
Whould you please Help me? 谁能帮我? Thank you. 谢谢。
preg_match_all() by default returns the result in pattern order, which is not very convenient. 默认情况下,preg_match_all()以模式顺序返回结果,这不是很方便。 Pass the PREG_SET_ORDER flag so that the data is arranged in a more logical way: 传递PREG_SET_ORDER标志,以便以更合理的方式排列数据:
$newscontent='<span id="bodyHolder_newstextDetail_nwstxtPicPane"><a href="xxxxx" target="_blank"><img alt="xxxxx" title="xxxxx" src=\'xxxxxbb\' />';
$picinfo=preg_match_all('/<span\s+id="bodyHolder_newstextDetail_nwstxtPicPane"><a\s+href="(.*)"\s+target="_blank"><img\s+alt="(.*)"\s+title="(.*)"\s+src=\'(.*)\'\s+\/>/',$newscontent,$matches,PREG_SET_ORDER);
foreach ($matches as $match) {
$href = $match[1];
$alt = $match[2];
$title = $match[3];
$src = $match[4];
echo $title;
}
Your RegEx is correct, as the manual says, by default PREG_PATTERN_ORDER
is followed which orders results so that $matches[0]
is an array of full pattern matches, $matches[1]
is an array of strings matched by the first parenthesized subpattern, and so on. 如手册所述,您的RegEx是正确的,默认情况下会遵循PREG_PATTERN_ORDER
来对结果进行PREG_PATTERN_ORDER
,以便$matches[0]
是完整模式匹配的数组, $matches[1]
是由第一个带括号的子模式匹配的字符串的数组,等等。
So as in your case, $matches 1 will contain the href, $matches 2 will contain the alt and so on. 因此,根据您的情况,$ matches 1将包含href,$ matches 2将包含alt等。 Like, 喜欢,
for($i = 0; $i <= count($matches[0]); $i++ )
echo "href = {$matches[1][$i]}, alt = {$matches[2][$i]}";
$matches[0]
will contain the full matched strings. $matches[0]
将包含完整匹配的字符串。
BTW, it is always advisable to use an XML parser, try DOMDocument. 顺便说一句,始终建议使用XML解析器,请尝试使用DOMDocument。 The obligatory . 强制性的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.