0

我有以下格式的字符串:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

现在每个部分都可以是以下任何值:abc, "abc", (abc), NIL

其中 abc 是一个字符串,它也可能包含空格、括号、引号。

示例字符串:

TEXT "PLAIN" ("NAME" "file(1).txt") 无

将这样的字符串解析为数组的最佳方法是什么?IE

数组[0] = 文本

数组[1] = "平原"

数组[2] = ("名称" "文件 (1).txt")

数组[3] = NIL

4

2 回答 2

1

此正则表达式将帮助您:

    $result=array();
    $subject = 'TEXT "PLAIN" (string with spaces) "string with other spaces" ("NAME" "file(1).txt") NIL';
    $regex = '
    /"([^"])+"                   # Match quote, followed by multiple non-quotes, ended by a quote.
    |(\([\w ]+\))                # Or match multiple words and spaces between parentheses
    |\(((?=")([^)]|(?>"|.))+)\)  # Or Match text between parentheses, ignore ending parenthese if inside a quote
    |\w+                         # Or match single words
    /x';

    preg_match_all($regex, $subject, $result, PREG_PATTERN_ORDER);
    $result = $result[0];
    print_r($result);

    print_r($result);

测试字符串:

 TEXT "PLAIN" (string with spaces) "string with other spaces" ("NAME" "file(1).txt") NIL

结果 :

    Array
    (
        [0] => TEXT
        [1] => "PLAIN"
        [2] => (string with spaces)
        [3] => "string with other spaces"
        [4] => ("NAME" "file(1).txt")
        [5] => NIL
    )
于 2012-05-07T09:32:06.407 回答
0

试试这个:

$input = 'TEXT "PLAIN" ("NAME" "file(1).txt") NIL';
$output = array();

$open = 0;
$parts = explode(' ', $input);
for ($i = $j = 0; $i < count($parts); $i++) {
    $open += substr_count($parts[$i], '(');
    $open -= substr_count($parts[$i], ')');

    $output[$j] .= $parts[$i];

    if ($open == 0) {
        $j++;
    }
}

var_dump($output);

我所做的很简单:通过切割空格将字符串分解成部分,然后确定我们是否在对偶内,或者在需要时重新组装零件。

于 2012-05-07T09:30:31.197 回答