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

Search for multiple string occurrence in String via PHP

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

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

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

我该怎么做?

Without using regex, something like this should work for returning the string positions:

<code>
    $html = "dddasdfdddasdffff";
    $needle = "asdf";
    $lastPos = 0;
    $positions = array();

    while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
        $positions[] = $lastPos;
        $lastPos = $lastPos + strlen($needle);
    }

    // Displays 3 and 10
    foreach ($positions as $value) {
        echo $value ."<br />";
    }
</code>

此解决方案不使用捕获组。相反,它使用 \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