views:

424

answers:

3

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

+1  A: 

There is preg_split for splitting files on regular expressions similar to explode, and then there is preg_match_all which does what you want.

Residuum
+2  A: 

preg_match_all:

$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
)
Sebastian P.
Sweet!
Petruza
+1  A: 

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.

Tom Haigh