我不擅长正则表达式,有人能帮我吗?
我在var$desc中有产品描述,类似于以下内容:
some text , some text, some text , some text
some text , some text , some text , some text
Product sku: 111111
some text , some text, some text , some text
我需要的是在文本"产品sku:"之后返回一个数字。如何做到这一点?
在PHP中,为了与任何正则表达式匹配,我们使用preg_match
、preg_match_all
函数:
<?php
preg_match('/Product sku:['s]*(['d]+)/i', 'some text , some text, some text , some text
some text , some text , some text , some text
Product SKU: 111111
some text , some text, some text , some text', $matches);
print_r($matches);
/**
Output:
Array ( [0] => Product SKU: 111111 [1] => 111111 ) // $matches[1] is what you need
*/
?>
注意正则表达式中的
i
,这是不区分大小写的。所以它与CCD_ 4&SKU
您可以在此处阅读有关此功能的更多信息:http://php.net/manual/en/function.preg-match.php
<?php
$subject = "some text , some text, some text , some text
some text , some text , some text , some text
Product sku: 111111 dhgfh
some text , some text, some text , some text";
$pattern = '/Product sku:'s*(?P<product_sku>'d+)/';
preg_match($pattern, $subject, $matches);
if (isset($matches['product_sku'])) {
echo 'Product sku: ' . $matches['product_sku'];
}
else {
echo 'Product sku not found!';
}
演示
请尝试以下代码:
if(preg_match('/Product sku:'s*?('d+)/mi',$strs,$matchs)){
echo $matchs[1];
}
希望这能帮助到你