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 之间没有空格,但输入字符串在那里有一个空格。

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

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

演示