honyovk
honyovk

Reputation: 2747

PHP - Wildcards in URI string

I am trying to create an API request handler that can read wildcards in a string. The ideal situation is something like this.

$myClass->httpGet('/account/[account_id]/list-prefs', function ($account_id) {
    // Do something with $account_id
});

Where [account_id] is the wild card. The actual URI would look like:

http://api.example.com/account/123456/list-prefs

The actual function looks like...

function httpGet($resource, $callback) {
    $URI = urldecode(str_replace('/'.$this->API_VERSION, '', $_SERVER['REQUEST_URI']));
    $match = preg_match_all('/\[([a-zA-Z0-9_]+)\]/', $resource, $array);
    if ($resource /*matches with wildcards*/ $URI) {
        // Do something with it.
    }
    ...
}

My problem is...

  1. I cannot figure out how to match the string within the function with the URI in order to call the callback.
  2. How to parse the string with the values supplied in the URI (replace [account_id] with 123456).

Upvotes: 1

Views: 909

Answers (1)

clime
clime

Reputation: 8885

I think you are missing something like:

tokens = array('[account_id]' => '/\[([a-zA-Z0-9_]+)\]/');

Then:

function replaceTokens($resource) {
    # get uri with tokens replaced for actual regular expressions and return it
}

function httpGet($resource, $callback) {
    $URI = urldecode(str_replace('/'.$this->API_VERSION, '', $_SERVER['REQUEST_URI']));        
    $uriRegex = replaceTokens($resource);
    $match = preg_match_all($uriRegex, $URI, $array);
    if ($match) {
        // Do something with it.
    }
}

Upvotes: 1

Related Questions