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 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效