簡體   English   中英

正則表達式 - 如何用逗號分隔字符串,省略括號中的逗號

[英]Regex - how to split string by commas, omitting commas in brackets

我有一個字符串,說:

$str = "myTemplate, testArr => [1868,1869,1870], testInteger => 3, testString => 'test, can contain a comma'"

它基本上代表了我需要解析的以逗號分隔的參數列表。

我需要用逗號分隔PHP中的這個字符串(可能使用preg_match_all )(但省略括號和引號中的那些),所以最終結果將是以下四個匹配的數組:

myTemplate
testArr => [1868,1869,1870]
testInteger => 3
testString => 'test, can contain a comma'

問題在於數組和字符串值。 因此,[]或“”或“”中的任何逗號都不應被視為分隔符。

這里有許多類似的問題,但我無法讓它適應這種特殊情況。 得到這個結果的正確正則表達式是什么? 謝謝!

您可以使用此基於外觀的正則表達式:

$str = "myTemplate, testArr => [1868,1869,1870], testInteger => 3, testString => 'test, can contain a comma'";

$arr = preg_split("/\s*,\s*(?![^][]*\])(?=(?:(?:[^']*'){2})*[^']*$)/", $str);

print_r( $arr );

這個正則表達式中使用了2種外觀:

  • (?![^][]*\\]) - 斷言逗號不在[...]
  • (?=(?:(?:[^']*'){2})*[^']*$) - 斷言逗號不在'...'

PS:假設我們沒有不平衡/嵌套/轉義的引號和括號。

RegEx演示

輸出:

Array
(
    [0] => myTemplate
    [1] => testArr => [1868,1869,1870]
    [2] => testInteger => 3
    [3] => testString => 'test, can contain a comma'
)

我傷口這樣做:

<?php

$str = "myTemplate, testArr => [1868,1869,1870], testInteger => 3, testString => 'test, can contain a comma'";


$pattern[0] = "[a-zA-Z]+,"; // textonly entry
$pattern[1] = "\w+\s*?=>\s*\[.*\]\s*,?"; // array type entry with value enclosed in square brackets
$pattern[2] = "\w+\s*?=>\s*\d+\s*,?"; // array type entry with decimal value
$pattern[3] = "\w+\s*?=>\s*\'.*\'\s*,?"; // array type entry with string value

$regex = implode('|', $pattern);

preg_match_all("/$regex/", $str, $matches);

// You can also use the one liner commented below if you dont like to use the array
//preg_match_all("/[a-zA-Z]+,|\w+\s*?=>\s*\[.*\]\s*,?|\w+\s*?=>\s*\d+\s*,?|\w+\s*?=>\s*\'.*\'\s*,?/", $str, $matches);
print_r($matches);

這更容易管理,如果需要,我可以輕松添加/刪除模式。 它會輸出像

Array
(
[0] => Array
    (
        [0] => myTemplate,
        [1] => testArr => [1868,1869,1870],
        [2] => testInteger => 3,
        [3] => testString => 'test, can contain a comma'
    )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM