本文介绍了正则表达式PHP多个实例和对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 $ user-> id ='1 {3} 4 {5} 6'; //可以是任何和更多,但{X} X是对
- 1表示一个常规的product_id,但对于最后的
结果不需要。
- {3}和{5}表示$ option
- 4和6表示$ value
- { 3} 4和{5} 6是成对的
我需要每一对数据库插入。
如何取出数值并运行以下数据库执行:
//类似于每个?作为选项和?作为$值做:
$ sth = $ this-> dbh-> prepare(insert into customers_basket_attributes
(
products_id,
products_options_id,
products_options_value_id
)
值(?,?,?));
$ sth-> execute(array($ user-> id,$ option,$ value));
当前接受来自的答案 * 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); ('1',?,?,?))插入到customers_basket_attributes(customers_id,products_id,products_options_id,products_options_value_id)中;
$ b $ sth = $ this-> dbh->
foreach($ output as $ option => $ value){
$ sth-> execute(array($ user-> id,$ option,$ value));
}
}
}
return json_encode(1);
似乎适用于准备好的报表。
$ b $你可以像这样使用preg_match_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);
$ / code>
OUPUT
<$ p (
[3] => 4
[5] => 6
)
I have
$user->id = '1{3}4{5}6';//could be any and more but {X}X are pairs
- 1 represents a regular product_id but is not needed for the endresult.
- {3} and {5} represents $option
- 4 and 6 represents $value
- {3}4 and {5}6 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.
解决方案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 )
这篇关于正则表达式PHP多个实例和对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!