通过PHP在String中搜索多个字符串

时间:2016-11-24 07:07:19

标签: regex model-view-controller preg-match-all substr

我正在使用MVC,php开发电子商务网站。我有一个叫做描述的字段。用户可以在说明字段中输入多个产品ID。

例如{productID = 34}, {productID = 58}

我正在尝试从此字段中获取所有产品ID。只是产品ID。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

此解决方案不使用捕获组。相反,它使用\K,以便完整的字符串元素成为使用括号捕获的元素。这是一个很好的做法,因为它将数组元素数量减少了50%。

$description="{productID = 34}, {productID = 58}";
if(preg_match_all('/productID = \K\d+/',$description,$ids)){
  var_export($ids[0]);
}

// output: array(0=>'34',1=>'58')

// \K in the regex means: keep text from this point

答案 1 :(得分:0)

/storage/emulated/0/