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

PHP regex preg_match numbers before a multiword string

我正在尝试从此样本中提取数字 203。

这是我运行正则表达式反对的样本:

<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>

这是我正在使用但不起作用的代码

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

刚回来

<pre>array ()</pre>

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

首先,在客户评论数之前的字符串中还有其他数字(如 4.3 out of 5 starsheight="12"),但 \D* 阻止匹配 - 它仅在以下情况下匹配字符串开头和评论数之间没有数字。

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

无需匹配包含客户评论数部分前后的任何字符串,只需匹配您关心的部分即可。

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

DEMO