如何从带有大括号的字符串中提取数字?

I have a test string which is something like this:

digit{digit}digit

I want to break this string into 3 variables. For example, 40{1}2 should be split into 40 1 2. The string could be as big as 2034{345}1245. I assume regex would be the best way to split this string.

Here's what I have so far:

$productID = preg_match('/(.*?){/', $product);
$productOptionID = preg_match('/{(.*?)}/', $product);
$optionValueID = preg_match('/}(.*?)/', $product);

No need for regular expressions here:

$str = '40{1}2';

sscanf($str, '%d{%d}%d', $part_1, $part_2, $part_3);
// $part_1 would equal: 40
// $part_2 would equal: 1
// $part_3 would equal: 2

With this method, the variables are already typecast to integers.

Try this instead:

preg_match('/^(\d+)\{(\d+)\}(\d+)$/', '123{456}789', $matches)
$productId = $matches[1];
$productOptionId = $matches[2];
$productValueId = $matches[3];

I would personally create a simple function that can manage the process of fetching the data from the string like so:

function processID($string)
{
    $result = array();
    $c = 0;
    for($i = 0; $i < strlen($string); $i++)
    {
         if(!isset($result[$c]))
         {
             $result[$c] = "";
         }

         if($string[$i] == "{" || $string[$i] == "}")
         {
             $c++;
             continue;
         }

         $result[$c] .= $string[$i];
    }
    return $result;
}

and then just use like:

$result = processID("2034{345}1245");

The outputted result would be like so:

array(3) {
  [0]=>
  string(4) "2034"
  [1]=>
  string(3) "345"
  [2]=>
  string(4) "1245"
}

and a working example can be found here: http://codepad.org/7k5tAzuy

How about preg_split :

$str = '123{456}789';
$arr = preg_split("/[{}]/", $str);
print_r($arr);

output:

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
)