2016-12-05 149 views
3

省略逗号我有一个字符串,说:正则表达式 - 如何用逗号分割的字符串,括号

$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' 

问题与数组和字符串值。因此[]或''或“”中的任何逗号都不应被视为分隔符。

这里有很多类似的问题,但我无法得到它在这种特殊情况下工作。什么是正确的正则表达式来获得这个结果?谢谢!

+1

你可以分享你的尝试? –

+2

你可以分享吗?你的数据看起来是什么 – RiggsFolly

+0

@PavneetSingh你已经将一个已经模糊的描述变成了别的东西。 **编辑问题时需要注意** – RiggsFolly

回答

2

你可以使用这个环视基于正则表达式:

$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个lookarounds:

  • (?![^][]*\]) - 断言逗号是不是里面[...]
  • (?=(?:(?:[^']*'){2})*[^']*$) - 断言逗号不在里面'...'

PS:这是假设我们没有不平衡/嵌套/转义的引号和括号。

RegEx Demo

输出:

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

我咬咬牙做这样的:

<?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' 
    ) 

) 
+0

看起来不错,谢谢! – Tomage

相关问题