查询字符串,如参数regex

时间:2013-08-12 11:04:43

标签: php regex

来自以下文字:

category=[123,456,789], subcategories, id=579, not_in_category=[111,333]

我需要一个正则表达式来获得类似的东西:

$params[category][0] = 123;
$params[category][1] = 456;
$params[category][2] = 789;
$params[subcategories] = ; // I just need to know that this exists
$params[id] = 579;
$params[not_category][0] = 111;
$params[not_category][1] = 333;

感谢大家的帮助。

PS

正如您所说,我澄清了结构和项目数量可能会发生变化。 基本上结构是:

key=value, key=value, key=value, ...

其中值可以是:

  • 单个值(例如category=123postID=123mykey=myvalue,...)
  • “数组”(例如category=[123,456,789]
  • 一个“布尔”,其中TRUE值是数组中存在“key”这一事实的假设(例如subcategories

4 个答案:

答案 0 :(得分:2)

这种方法应该足够灵活:

$str = 'category=[123,456,789], subcategories, id=579, not_in_category=[111,333]';
$str = preg_replace('#,([^0-9 ])#',', $1',$str); //fix for string format with no spaces (count=10,paginate,body_length=300)
preg_match_all('#(.+?)(,[^0-9]|$)#',$str,$sections); //get each section
$params = array();
foreach($sections[1] as $param)
{
    list($key,$val) = explode('=',$param); //Put either side of the "=" into variables $key and $val
    if(!is_null($val) && preg_match('#\[([0-9,]+)\]#',$val,$match)>0)
    {
        $val = explode(',',$match[1]); //turn the comma separated numbers into an array
    }
    $params[$key] = is_null($val) ? '' : $val;//Use blank string instead of NULL
}
echo '<pre>'.print_r($params,true).'</pre>';
var_dump(isset($params['subcategories']));

输出:

Array
(
    [category] => Array
        (
            [0] => 123
            [1] => 456
            [2] => 789
        )

    [subcategories] => 
    [id] => 579
    [not_in_category] => Array
        (
            [0] => 111
            [1] => 333
        )

)

bool(true) 

Alternate(进程前没有字符串操作):

$str = 'count=10,paginate,body_length=300,rawr=[1,2,3]';
preg_match_all('#(.+?)(,([^0-9,])|$)#',$str,$sections); //get each section
$params = array();
foreach($sections[1] as $k => $param)
{
    list($key,$val) = explode('=',$param); //Put either side of the "=" into variables $key and $val
    $key = isset($sections[3][$k-1]) ? trim($sections[3][$k-1]).$key : $key; //Fetch first character stolen by previous match
    if(!is_null($val) && preg_match('#\[([0-9,]+)\]#',$val,$match)>0)
    {
        $val = explode(',',$match[1]); //turn the comma separated numbers into an array
    }
    $params[$key] = is_null($val) ? '' : $val;//Use blank string instead of NULL
}
echo '<pre>'.print_r($params,true).'</pre>';

另一个备用:在安全处理之前完全重新格式化字符串

$str = 'count=10,paginate,body_length=300,rawr=[1, 2,3] , name = mike';
$str = preg_replace(array('#\s+#','#,([^0-9 ])#'),array('',', $1'),$str); //fix for varying string formats
preg_match_all('#(.+?)(,[^0-9]|$)#',$str,$sections); //get each section
$params = array();
foreach($sections[1] as $param)
{
    list($key,$val) = explode('=',$param); //Put either side of the "=" into variables $key and $val
    if(!is_null($val) && preg_match('#\[([0-9,]+)\]#',$val,$match)>0)
    {
        $val = explode(',',$match[1]); //turn the comma separated numbers into an array
    }
    $params[$key] = is_null($val) ? '' : $val;//Use blank string instead of NULL
}
echo '<pre>'.print_r($params,true).'</pre>';

答案 1 :(得分:0)

您也可以使用JSON,它在PHP中是原生的:http://php.net/manual/fr/ref.json.php

这将更容易;)

答案 2 :(得分:0)

<?php
$subject = "category=[123,456,789], subcategories, id=579, not_in_category=[111,333]";
$pattern = '/category=\[(.*?)\,(.*?)\,(.*?)\]\,\s(subcategories),\sid=(.*?)\,\snot_in_category=\[(.*?)\,(.*?)\]/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?> 

我认为这会让你的比赛结束......实际上没有测试它,但它可能是一个很好的起点。

然后,您只需将匹配项推送到所需数组中的正确位置即可。还要测试subcategories字符串是否存在strcmp或其他内容......

另外,请注意我假设您的subject字符串具有固定结构的类型...如果它经常更改,您将需要更多...

答案 3 :(得分:0)

$str = 'category=[123,456,789], subcategories, id=579, not_in_category=[111,333]';
$main_arr = preg_split('/(,\s)+/', $str);
$params = array();
foreach( $main_arr as $value) {
    $pos = strpos($value, '=');
    if($pos === false) {
        $params[$value] = null;
    } else {
        $index_part = substr($value, 0, $pos);
        $value_part = substr($value, $pos+1, strlen($value));
        $match = preg_match('/\[(.*?)\]/', $value_part,$xarr);
        if($match) {
            $inner_arr = preg_split('/(,)+/', $xarr[1]);
            foreach($inner_arr as $v) {
                $params[$index_part][] = $v;
            }
        } else {
            $params[$index_part] = $value_part;
        }

    }
}

print_r( $params );

输出

Array
(
    [category] => Array
        (
            [0] => 123
            [1] => 456
            [2] => 789
        )

    [subcategories] => 
    [id] => 579
    [not_in_category] => Array
        (
            [0] => 111
            [1] => 333
        )

)