October 20, 200916 yr Trying to split a URIs folders using preg. I mange to split out the domain and filename but can't seem to split out the folders; I only manage to store the last one. Surely there's a quick mod to my expression to get it right! $matches = array(); $url = '/alpha/beta/gamma/delta/epsilon/'; $pattern = '!^(\/[-0-9a-z]*)+\/$!'; preg_match_all($pattern,$url,$matches); This currently gets me: array(1 => /alpha/beta/gamma/delta/, 2 => /epsilon); And I want: array(1 => /alpha, 2 => /beta, 3 => /gamma, 4 => /delta );
October 20, 200916 yr At first this sounded like a greedy operator problem, but then I tried it and realised it didn't help setting to ungreedy - I don't think the expression is quite correct. I think this is a better solution (which works): $pattern = '!/([^/]+)!'; //$pattern = '!/([-0-9a-z]+)!'; // use this if you want to be specific about allowed characters $url = '/alpha/beta/gamma/delta/epsilon/'; preg_match_all($pattern,$url,$matches); print_r($matches[0]); This then outputs: Array ( [0] => /alpha [1] => /beta [2] => /gamma [3] => /delta [4] => /epsilon ) which I assume is what you wanted?
October 22, 200916 yr This will also work... <?php $matches = array(); $url = '/alpha/beta/gamma/delta/epsilon/'; $pattern = '%/[^/]+%'; preg_match_all($pattern,$url,$matches); echo '<pre>'.print_r($matches, true).'</pre>';
October 22, 200916 yr Could you not just use preg_split()? or even just explode() This is a good point actually, one which I'd overlooked by concentrating too hard on the regex. Using explode() would be easier and give better performance since it doesn't need to compile your pattern and run the regex parser. For example: $url = '/alpha/beta/gamma/delta/epsilon/'; $parts = explode("/",$url); print_r($parts); which outputs: Array ( [0] => [1] => alpha [2] => beta [3] => gamma [4] => delta [5] => epsilon [6] => ) You can obviously remove the empty items (or trim the original / from the front and end of $url) and add the missing slashes if you want.
October 22, 200916 yr Yeah it was only after I looked at what needed to be output from the string that i realised it was far simpler exploding, and I'm sure that the / is not actually a requirement for whatever the OP is needing
Create an account or sign in to comment