2016-02-25 104 views
0

我想从此示例中提取数字203。PHP正则表达式preg_match数字之前的多字字符串

这里是我正在对正则表达式的示例:

<span class="crAvgStars" style="white-space:no-wrap;"><span class="asinReviewsSummary" name="B00KFQ04CI" ref="cm_cr_if_acr_cm_cr_acr_pop_" getargs="{&quot;tag&quot;:&quot;&quot;,&quot;linkCode&quot;:&quot;sp1&quot;}"> 

<a href="http://rads.stackoverflow.com/amzn/click/B00KFQ04CI" target="_top"><img src="https://images-na.ssl-images-amazon.com/images/G/01/x-locale/common/customer-reviews/ratings/stars-4-5._CB192238104_.gif" width="55" alt="4.3 out of 5 stars" align="absbottom" title="4.3 out of 5 stars" height="12" border="0" /></a>&nbsp;</span>(<a href="http://rads.stackoverflow.com/amzn/click/B00KFQ04CI" target="_top">203 customer reviews</a>)</span> 

这里是我用不工作

preg_match('/^\D*(\d+)customer reviews.*$/',$results[0], $clean_results); 
echo "<pre>"; 
print_r($clean_results); 
echo "</pre>"; 
//expecting 203 

代码它只是返回

<pre>array()</pre> 
+0

' '/(\ d +)顾客评论\ B /'' –

+0

preg_match'的'结果是一个数组,所以将其打印出来,你必须使用'print_r',不' echo'。第一个括号组在'$ clean_results [1]' – fusion3k

+0

真棒!这是答案。我很高兴地标记这个! @WiktorStribiżew – user1669039

回答

1

您的正则表达式有两个问题。

首先,有字符串中的其他数字的顾客评论(如4.3 out of 5 starsheight="12")号码前,但\D*防止匹配 - 它只是如果没有数字的字符串的开头和之间的任何比赛评论数。

其次,在(\d+)customer reviews之间没有空格,但输入字符串在那里有一个空格。

在包含顾客评论数量的部分之前和之后,没有必要匹配任何字符串,只需匹配您关心的部分即可。

preg_match('/(\d+) customer reviews/',$results[0], $clean_results); 
$num_reviews = $clean_results[1]; 

DEMO

相关问题