0

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not working, the outcome for this is: Array ( [1] => table [2] => tr:n(1-2) )
Same issue for the second option :/
If it doesn't work for you, why is it accepted?
0

You can use

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

See the regex demo. This pattern matches a / and then captures into Group 1 1 or more characters other than /.

The issue you had is that the trailing slash was consumed. Also, you used greedy matching, that just grabbed too much.

Ideone demo:

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

2 Comments

Why is it saved into $matches[1]? I would have expected to have the first occurence in $matches[0] and the second one in $matches[1]
That depends on how many parts you have. Is it always just 2? Then '~/([^/]+)/([^/]+)~' can help. See this demo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.