phpregexpreg-split

PHP Regex / delimiter


I have a string "/test:n(0-2)/div/" which I want to split via Regex into an array with function preg_split(). The output should be like this:

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

However it seems not to be that easy as I have thought it is. Here are my attempts: https://regex101.com/r/iP2lD8/1

$re = '/\/.*\//';
$str = '/test:n(0-2)/div/';
$subst = '';

$result = preg_replace($re, $subst, $str, 1);

echo "The result of the substitution is ".$result;

Full match 0-17:
/test:n(0-2)/div/

What am I doing wrong?


Solution

  • 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);
    print_r($result[1]);
    

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