regex-php多实例和多对

regex-php多实例和多对,php,regex,foreach,Php,Regex,Foreach,我有$user->id='1{3}4{5}6'//可以是任意多个,但{X}X是成对的 1表示常规产品标识,但不需要用于最终产品 结果 {3} 和{5}表示$option 4和6代表美元价值 {3} 4和{5}6是成对的 我需要为每一对插入一个db 如何取出这些值并运行以下db执行: //Something like for each ?? as option and ?? as $value do: $sth = $this->dbh->prepare("insert into

我有
$user->id='1{3}4{5}6'//可以是任意多个,但{X}X是成对的

  • 1表示常规产品标识,但不需要用于最终产品 结果
  • {3} 和{5}表示$option
  • 4和6代表美元价值
  • {3} 4和{5}6是成对的
我需要为每一对插入一个db

如何取出这些值并运行以下db执行:

//Something like for each ?? as option and ?? as $value do:
$sth = $this->dbh->prepare("insert into customers_basket_attributes 
( 
products_id,
products_options_id, 
products_options_value_id
) 
values (?, ?, ?)");
$sth->execute(array($user->id, $option, $value));
当前代码和接受的答案来自*Anubhava*


似乎适用于准备好的语句。

您可以像这样使用
preg\u match\u all

$str = '1{3}4{5}6';
if (preg_match_all('/\{(\d+)\}(\d+)/u', $str, $m )) {
   $output = array_combine ( $m[1], $m[2] );
   print_r($output);
}
输出
谢谢你,我只是在玩它,但是对于regex我没有吃足够的奶酪:)不客气。如果它对你有用,请考虑接受这个答案。实际上,我需要首先找到一种方法来实现它,以便它运行所需的DB查询。但是,如果你的方法是正确的,我一定会接受它。噢,这很容易。从我展示的代码中,您只需要
foreach($k=>v输出){dbInsert($k,$v);}
(假设函数
dbInsert
插入单个键值对)。
$str = '1{3}4{5}6';
if (preg_match_all('/\{(\d+)\}(\d+)/u', $str, $m )) {
   $output = array_combine ( $m[1], $m[2] );
   print_r($output);
}
Array
(
    [3] => 4
    [5] => 6
)