我对正则表达式非常苛刻,有人可以帮助我吗?
我在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: ”之后返回一个数字。怎么做到这一点?
答案 0 :(得分:1)
在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
,它不区分大小写。所以 它匹配sku
和&amp;SKU
您可以在此处详细了解此功能:http://php.net/manual/en/function.preg-match.php
答案 1 :(得分:0)
<?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!';
}
答案 2 :(得分:0)
请尝试以下代码:
if(preg_match('/Product sku:\s*?(\d+)/mi',$strs,$matchs)){
echo $matchs[1];
}
希望这可以帮到你!