如何从字符串中提取多个变量值(PHP)

时间:2016-03-21 09:41:47

标签: php arrays string

例如:

$string = "AND (pr.StatusCode <> 'U') AND ((pr.pkBrand = 9) OR (pr.pkBrand = 70)) AND ((pr.pkCategory = 55) OR (pr.pkCategory = 56)) AND (pr.StatusCode <> 'D')";

我需要提取与pkBrand相关的值,即9&amp; 70推入阵列以供其他地方使用,以及pkCategory的值,即55&amp; 56再次成为一个单独的阵列,供其他地方使用。

我该怎么办呢。

2 个答案:

答案 0 :(得分:3)

也许你可以这样做:

$string = "AND (pr.StatusCode <> 'U') AND ((pr.pkBrand = 9) OR (pr.pkBrand = 70)) AND ((pr.pkCategory = 55) OR (pr.pkCategory = 56)) AND (pr.StatusCode <> 'D')";
preg_match_all("/pr.pkBrand = (\d+)|pr.pkCategory = (\d+)/", $string, $matches, PREG_SET_ORDER);

$matches数组将如下所示:

array(4) { [0] => array(2) { [0] => string(14) "pr.pkBrand = 9" [1] => string(1) "9" } [1] => array(2) { [0] => string(15) "pr.pkBrand = 70" [1] => string(2) "70" } [2] => array(3) { [0] => string(18) "pr.pkCategory = 55" [1] => string(0) "" [2] => string(2) "55" } [3] => array(3) { [0] => string(18) "pr.pkCategory = 56" [1] => string(0) "" [2] => string(2) "56" } }

然后,您可以从中提取所需的值。

答案 1 :(得分:1)

这不那么简洁,但它的目的是无论字段名称如何都可以工作:

<?php
$string = "AND (pr.StatusCode <> 'U') AND ((pr.pkBrand = 9) OR (pr.pkBrand = 70)) AND ((pr.pkCategory = 55) OR (pr.pkCategory = 56)) AND (pr.StatusCode <> 'D')";
$newString=trim(str_replace(')','',str_replace('(','',str_replace('OR','',str_replace('AND','',$string)))));
$tab=explode('pr.',$newString);
foreach($tab as $value) {
 $value=trim(str_replace(' ','',str_replace('\'','',$value)));
 $tab2[]=$value;
}
/*echo '<pre>';
var_dump($tab2);
echo '</pre>';*/
$operators=['!=','<>','<','>','='];
foreach ($tab2 as $index=>$value) {
 foreach ($operators as $operator) {
    $found=0;
    $explode=explode($operator,$value);
     if (count($explode)==1) {}//not the good one
     else {
      $found=1;
      break;
     }
 }
 if ($found==1) $newTab[$explode[0]][$index]=$explode[1];
}


echo '<pre>';
var_dump($newTab);
echo '</pre>';

?>

会给你:

array(3) {
  ["StatusCode"]=>
  array(2) {
    [1]=>
    string(1) "U"
    [6]=>
    string(1) "D"
  }
  ["pkBrand"]=>
  array(2) {
    [2]=>
    string(1) "9"
    [3]=>
    string(2) "70"
  }
  ["pkCategory"]=>
  array(2) {
    [4]=>
    string(2) "55"
    [5]=>
    string(2) "56"
  }
}