Can preg_match() (or other php regex function) match a variable number of parenthesized subpatterns?
-
18-09-2019 - |
Question
Suppose I have '/srv/www/site.com/htdocs/system/application/views/'
and want to test it against a regexp that matches each directory name in the path?
Something like this pattern: '(/[^/])'
That yields an array with 'srv','www','site.com'...
etc.
PS: the regexp syntax I wrote is just to illustrate, it's not tested and surely wrong, but just to give an idea.
PS2: I know there's explode()
but let's see if we can do this with a regexp (it's useful for other languages and frameworks which don't have explode).
Solution
$str = '/srv/www/site.com/htdocs/system/application/views/';
preg_match_all('/\/([^\/]+)/', $str, $matches);
// $matches[0] contains matching strings
// $matches[1] contains first subgroup matches
print_r($matches[1]);
Output:
Array
(
[0] => srv
[1] => www
[2] => site.com
[3] => htdocs
[4] => system
[5] => application
[6] => views
)
OTHER TIPS
There is preg_split
for splitting files on regular expressions similar to explode, and then there is preg_match_al
l which does what you want.
I don't think you can, but you could instead use preg_match_all() to get multiple matches from a regular expression. There is also preg_split() which may be more appropriate.