marius marius - 6 months ago 15
PHP Question

PHP Regex / delimiter

I have a string

which I want to split via Regex into an array with function
. The output should be like this:

output = {

However it seems not to be that easy as I have thought it is. Here are my attempts:

What am I doing wrong?


Just use explode():

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

array_filter() removes the empties from the / on either end. Alternately you could trim() it:

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

But to answer the question, you would just use / as the pattern for preg_split() and either escape the / as in /\// or use different delimiters:

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

Another way depending on your needs and complexity of the string contents:

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

$result[0] is an array of full matches and $result[1] is an array of the first capture group (). If there were more capture groups you would have more array elements in $result.