我有这个字符串:
EXAMPLE|abcd|[!PAGE|title]
我想这样分割:
Array
(
[0] => EXAMPLE
[1] => abcd
[2] => [!PAGE|title]
)
怎么做?谢谢你。
DEMO
如果你不需要比你说的更多的东西,就像解析一个CSV,但用|
作为分隔符,[
作为"
,所以:('[.*?']+|[^'|]+)(?='||$)
将做我认为的工作。
编辑:改变了正则表达式,现在它接受像[asdf]].[]asf]这样的字符串
解释:
-
('[.*?']+|[^'|]+)
->这个分为2部分:(将匹配1.1或1.2)
1.1'[.*?']+
->匹配[
和]
之间的所有内容
1.2[^'|]+
->将匹配|
所包含的所有内容 -
(?='||$)
->这将告诉正则表达式,在它旁边必须是|
或字符串的结尾,这样将告诉正则表达式接受像前面的例子一样的字符串。
在您的示例中,您可以使用('[.*?']|[^|]+)
。
preg_match_all("#('[.*?']|[^|]+)#", "EXAMPLE|abcd|[!PAGE|title]", $matches);
print_r($matches[0]);
// output:
Array
(
[0] => EXAMPLE
[1] => abcd
[2] => [!PAGE|title]
)
使用(?<='||^)((('[.*'|?.*'])|(.+?)))(?='||$)
(?<='||^) Positive LookBehind
1st alternative: '|Literal `|`
2nd alternative: ^Start of string
1st Capturing group ((('[.*'|?.*'])|(.+?)))
2nd Capturing group (('[.*'|?.*'])|(.+?))
1st alternative: ('[.*'|?.*'])
3rd Capturing group ('[.*'|?.*'])
'[ Literal `[`
. infinite to 0 times Any character (except newline)
'| 1 to 0 times Literal `|`
. infinite to 0 times Any character (except newline)
'] Literal `]`
2nd alternative: (.+?)
4th Capturing group (.+?)
. 1 to infinite times [lazy] Any character (except newline)
(?='||$) Positive LookAhead
1st alternative: '|Literal `|`
2nd alternative: $End of string
g modifier: global. All matches (don't return on first match)
非正则表达式解决方案:
$str = str_replace('[', ']', "EXAMPLE|abcd|[!PAGE|title]");
$arr = str_getcsv ($str, '|', ']')
如果你希望看到类似"[[]]"这样的内容,你必须用斜杠转义内括号,在这种情况下,regex可能是更好的选择。
http://de2.php.net/manual/en/function.explode.php
$array= explode('|', $string);