繁体   English   中英

如何从php中的给定字符串中提取条件运算符?

[英]How to extract conditional operators from the given string in php?

我有一个函数调用extractValues(),并有一个带有条件运算符的数组来传递它。 我真正需要的是,拆分字符串和运算符。 例如:

$arr = array('username='=> 'Alex','id >'=>'4');
extractValues($arr);

我需要将$ arr键中可用的运算符和字符串拆分并存储到两个单独的变量中。 请记住,所有阵列键都是动态的。 字符串和条件运算符之间可能有空格,也可能没有。

数组键中期望的运算符为:

$operators = array('=','!=', '<', '<=', '>', '>=', 'like', 'clike', 'slike', 'not', 'is', 'in', 'between', 'and', 'or');

除了其他可能性之外,您还可以使用preg_match()实现此目的。 我不确定我是否理解您的问题正确,但是我已经准备好了示例,应该会有所帮助。 它将原始数组转换为具有以下结构的数组:

array(
  array('key', 'operator', 'value'),
  array('key', 'operator', 'value'),
  array('key', 'operator', 'value'),
  // ...
)

代码如下:

$arr = array('username='=> 'Alex','id >'=>'4');
$result = extractValues($arr);
var_dump($result);

function extractValues($arr) {
    $pattern  = '/([A-Za-z_]+[A-Za-z_0-9]?)[ ]?(!=|=|<=|<|>=|';
    $pattern .= '>|like|clike|slike|not|is|in|between|and|or)/';

    $result = array();
    foreach($arr as $key => $value) {
        preg_match($pattern, $key, $matches);
        $result []= array($matches[1], $matches[2], $value);
    }

    return $result;
}

输出如下:

array(2) {
  [0] =>
  array(3) {
    [0] =>
    string(8) "username"
    [1] =>
    string(1) "="
    [2] =>
    string(4) "Alex"
  }
  [1] =>
  array(3) {
    [0] =>
    string(2) "id"
    [1] =>
    string(1) ">"
    [2] =>
    string(1) "4"
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM