【问题标题】:PHP equivalent of Python's shlex.splitPHP 等效于 Python 的 shlex.split
【发布时间】:2013-02-25 19:18:31
【问题描述】:

我正在尝试解析包含空格分隔的键=>值对的文件,格式如下:

host=db test="test test" blah=123

通常,此文件由 Python 摄取并使用 shlex.split 解析,但我一直无法找到 PHP 等效项,并且我尝试使用 preg_splitstrtok 将其逻辑化的尝试效率不高.

是否有与 Python 的shlex.split 等效的 PHP?

【问题讨论】:

  • 据我所知,没有函数可以产生您正在寻找的确切行为,但是,执行这两个步骤应该是微不足道的。您可以使用preg_match_all 将字符串分解为数组,然后循环遍历数组,将其转换为您需要的格式。
  • 类似Regular expression for matching name value pairs 的东西,除了,\s 代替,这样preg_match_all 就可以工作了。

标签: php shlex


【解决方案1】:

不幸的是,没有内置的 PHP 函数可以原生处理这样的分隔参数。但是,您可以使用一些正则表达式和一些数组遍历非常快速地构建一个。这只是一个示例,仅适用于您提供的字符串类型。任何额外的条件都需要添加到正则表达式中,以确保它正确匹配模式。您可以在遍历文本文件时轻松调用此函数。

/**
 * Parse a string of settings which are delimited by equal signs and seperated by white
 * space, and where text strings are escaped by double quotes.
 *  
 * @param  String $string String to parse
 * @return Array          The parsed array of key/values
 */
function parse_options($string){
    // init the parsed option container
    $options = array();

    // search for any combination of word=word or word="anything"
    if(preg_match_all('/(\w+)=(\w+)|(\w+)="(.*)"/', $string, $matches)){
        // if we have at least one match, we walk the resulting array (index 0)
        array_walk_recursive(
            $matches[0], 
            function($item) use (&$options){
                // trim out the " and explode at the =
                list($key, $val) = explode('=', str_replace('"', '', $item));
                $options[$key] = $val;
            }
        );   
    }

    return $options;
}

// test it
$string = 'host=db test="test test" blah=123';

if(!($parsed = parse_options($string))){
    echo "Failed to parse option string: '$string'\n";
} else {
    print_r($parsed);
}

【讨论】:

  • 这是一个非常糟糕的答案,因为相当于shlex.split。因为它甚至无法将a "b c" 处理成["a", "b c"]
【解决方案2】:

你可以试试这个 PHP 版本的 shlex 扩展。

https://github.com/zimuyang/php-shlex

例子

<?php

$s = "foo#bar";
$ret = shlex_split($s, true);

var_dump($ret);

?>

上面的例子会输出:

array(1) {
  [0] =>
  string(3) "foo"
}

【讨论】:

    猜你喜欢
    • 2020-07-03
    • 2012-07-18
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2012-06-28
    • 2011-03-13
    相关资源
    最近更新 更多