views:

40

answers:

2

Hi, I have url like this

/cp/foo-bar/another-testing

how to parse it with the pattern

/cp/{0}-{1}/{2}

results will be

0:foo
1:bar
2:another-testing

I need a global solution to parse all kind of url with a pattern like that. I mean using {0}, {1} flag.

+2  A: 
if (preg_match('#/cp/([^/]+?)-([^/]+?)/([^/]+)#'), $url, $matches)) {
    //look into $matches[1], $matches[2] and $matches[3]
}
Artefacto
Hi, what is the # character mean?
StoneHeart
@Stone It's just a delimiter. See http://pt.php.net/manual/en/regexp.reference.delimiters.php
Artefacto
+1  A: 

Instead of using {0}, {1}, {2}, I offer a new way: using {$s[0]}, {$s[1]}, {$s[2]}:

$your_url = '/cp/foo-bar/another-testing';
$s = explode('/', $your_url);
if(!$s[0])
     array_shift($s);
if($temp = array_pop($s))
     $s[] = $temp;
//then
$result = "/cp/{$s[0]}-{$s[1]}/{$s[2]}";
Bang Dao