tags:

views:

42

answers:

4

Hi everybody!

I have to set some routing rules in my php application, and they should be in the form /%var/something/else/%another_var

In other words i beed a regex that returns me every URI piece marked by the % character, String marked by % represent var names so they can be almost every string.

another example: from /%lang/module/controller/action/%var_1 i want the regex to extract lang and var_1

i tried something like

/.*%(.*)[\/$]/

but it doesn't work.....

+1  A: 
$str='/%var/something/else/%another_var';
$s = explode("/",$str);
$whatiwant = preg_grep("/^%/",$s);
print_r($whatiwant);
ghostdog74
+1 More elegant than mine because of the `preg_grep`.
Pekka
+1  A: 

Seeing as it's routing rules, and you may need all the pieces at some point, you could also split the string the classical way:

$path_exploded = explode("/", $path);
foreach ($path_exploded as $fragment) if ($fragment[0] == "%") 
  echo "Found $fragment";
Pekka
thank you it works (and it's very simple, i need to sleep now) =)
fatmatto
A: 

You can use:

$str = '/%lang/module/controller/action/%var_1';    
if(preg_match('@/%(.*?)/[^%]*%(.*?)$@',$str,$matches)) {
        echo "$matches[1] $matches[2]\n"; // prints lang var_1    
}
codaddict
+1  A: 

I don’t see the need to slow down your script with a regex … trim() and explode() do everything you need:

function extract_url_vars($url)
{
    if ( FALSE === strpos($url, '%') )
    {
        return $url;
    }

    $found = array();
    $parts = explode('/%', trim($url, '/') );

    foreach ( $parts as $part )
    {
        $tmp     = explode('/', $part);
        $found[] = ltrim( array_shift($tmp), '%');
    }

    return $found;
}

// Test
    print_r( extract_url_vars('/%lang/module/controller/action/%var_1') );

// Result:
Array
(
    [0] => lang
    [1] => var_1
)
toscho