HenryW
HenryW

Reputation: 3761

regex php multiple instances and pairs

I have $user->id = '1{3}4{5}6';//could be any and more but {X}X are pairs

I require for each pair a db insertion.

How can i take the values out and run the following db execution:

//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));

Current code with the accepted answer from *Anubhava*

if ($user->attr = 1) {
if (preg_match_all('/\{(\d+)\}(\d+)/u', $user->id, $m )) {
 $option1 = $m[1];
 $value2 = $m[2];
 $output = array_combine ( $option1, $value2 );

$sth = $this->dbh->prepare("insert into customers_basket_attributes (customers_id, products_id, products_options_id, products_options_value_id) values ('1', ?, ?, ?)");
 foreach($output as $option => $value) {    
$sth->execute(array($user->id, $option, $value));
}       

}
}
return json_encode(1);

Seems to work for prepared statements.

Upvotes: 1

Views: 54

Answers (1)

anubhava
anubhava

Reputation: 785641

You can use preg_match_all like this:

$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);
}

OUPUT

Array
(
    [3] => 4
    [5] => 6
)

Upvotes: 2

Related Questions