2016-05-27 123 views
0

我有一个字符串"/test:n(0-2)/div/",我想通过正则表达式分割成一个数组与功能preg_split()。输出应该是这样的:PHP的正则表达式/分隔符

output = { 
[0]=>"test:n(0-2)" 
[1]=>"div" 
} 

然而,它似乎并不像我想的那么容易。以下是我的尝试:https://regex101.com/r/iP2lD8/1

我在做什么错?

回答

3

只需使用explode()

$result = array_filter(explode('/', $string)); 

array_filter()消除在两端从/空瓶。或者你可以trim()它:

$result = explode('/', trim($string, '/')); 

但是,为了回答这个问题,你只用/为图案的preg_split(),要么逃避//\//或使用不同的分隔符:

$result = array_filter(preg_split('#/#', $string)); 

另一个方式取决于你的需求和字符串内容的复杂程度:

preg_match_all('#/([^/]+)#', $string, $result); 
print_r($result[1]); 

$result[0]是完整匹配数组,$result[1]是第一个捕获组()的数组。如果有更多的捕获组,你会在$result中有更多的数组元素。

+0

不工作,这样做的结果是:数组 ( [1] =>表 [2] => TR:N(1-2) ) – marius

+0

同样的问题第二个选项:/ – marius

+0

不,他们都工作:https://3v4l.org/4jFAv不知道你做错了什么。 – AbraCadaver

0

您可以使用

'~/([^/]+)~' 

regex demo。该模式匹配/,然后捕获到组1中除/以外的1个或更多字符。

您遇到的问题是消耗了斜线。此外,你使用了贪婪的匹配,只是抓得太多。

Ideone demo

$re = '~/([^/]+)~'; 
$str = "/test:n(0-2)/div/"; 
preg_match_all($re, $str, $matches); 
print_r($matches[1]); 
+0

为什么它保存到$ matches [1]中?我预计会有第一次出现在$匹配[0],第二次出现在$匹配[1] – marius

+0

这取决于你有多少部分。它总是只有2?然后[''〜/([^ /] +)/([^ /] +)〜''](https://regex101.com/r/nV6eC7/2)可以提供帮助。请参阅[**本演示**](http://ideone.com/oDMipZ)。 –