次の形式の文字列があります。
xxx xxx xxx xxx
各部分は次の値のいずれかになります: abc、"abc"、(abc)、NIL
abc は、スペース、括弧、引用符を含む文字列です。
文字列の例:
TEXT "PLAIN" ("NAME" "file(1).txt") NIL
このような文字列を解析して配列にする最良の方法は何ですか? すなわち
配列[0] = テキスト
配列[1] = "プレーン"
配列[2] = ("名前" "ファイル(1).txt")
配列[3] = NIL
この正規表現は次のことに役立ちます。
$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
)
これを試して:
$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);
私がしていることは単純です: スペースを切り取って文字列をパーツに分解し、必要に応じてパラテシスの内側にいるかどうかを判断します。