douju1997 2016-02-25 23:13
浏览 51
已采纳

在多字符串字符串之前的PHP正则表达式preg_match数字

I am trying to extract the number 203 from this sample.

Here is the sample I am running the regex against:

<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="https://www.amazon.com/Moto-1st-Gen-Screen-Protector/product-reviews/B00KFQ04CI/ref=cm_cr_if_acr_cm_cr_acr_img/181-2284807-1957201?ie=UTF8&linkCode=sp1&showViewpoints=1" 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="https://www.amazon.com/Moto-1st-Gen-Screen-Protector/product-reviews/B00KFQ04CI/ref=cm_cr_if_acr_cm_cr_acr_txt/181-2284807-1957201?ie=UTF8&linkCode=sp1&showViewpoints" target="_top">203 customer reviews</a>)</span>

Here is the code I am using that does not work

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

It is just returning

<pre>array ()</pre>
  • 写回答

1条回答 默认 最新

  • doudao1950 2016-02-26 00:58
    关注

    Your regexp has two problems.

    First, there are other numbers in the string before the number of customer reviews (like 4.3 out of 5 stars and height="12"), but \D* prevents matching that -- it only matches if there are no digits anywhere between the beginning of the string and the number of reviews.

    Second, you have no space between (\d+) and customer reviews, but the input string has a space there.

    There's no need to match any of the string before and after the part that contains the number of customer reviews, just match the part you care about.

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

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e
  • ¥15 使用deepspeed训练,发现想要训练的参数没有梯度