Hey guys! I need help with regular expressions, etc. I need to extract virtual keys from url, some kind of router in the application. Here are the options:
Rule: /books/:category/:id/:keyname Data: /books/php/12345/this-is-a-test-keyname
The result should be something like this:
array( 'category' => 'php', 'id' => '12345', 'keyname' => 'this-is-a-test-keyname' );
So the question is: how can I do this in php?
PS Rule combinations may vary. So, the main keys are the words with the symbol ":". eg:
/book-:id/:category/:keyname /book/:id_:category~:keyname
PS 2: This is a piece of code that I had before. It works, but is not flexible.
function rule_process($rule, $data) { // extract chunks $ruleItems = explode('/',$rule); $dataItems = explode('/',$data); // remove empty items array_clean(&$ruleItems); array_clean(&$dataItems); // rule and data supposed to have the same structure if (count($ruleItems) == count($dataItems)) { $result = array(); foreach($ruleItems as $ruleKey => $ruleValue) { // check if the chunk is a key if (preg_match('/^:[\w]{1,}$/',$ruleValue)) { // ok, found key, adding data to result $ruleValue = substr($ruleValue,1); $result[$ruleValue] = $dataItems[$ruleKey]; } } if (count($result) > 0) return $result; unset($result); } return false; } function array_clean($array) { foreach($array as $key => $value) { if (strlen($value) == 0) unset($array[$key]); } }
In fact, this version of the router may be enough for me, but they are just wondering how to make a flexible decision. By the way, some tests: (30 times out of 10,000 operations):
TEST
So, this is fast enough. Im testing on a regular laptop. So, for sure - this one can be used on a real site.
Any other solutions?