I have a URL that is hardcoded via a config which I extract into a config:
$url = 'http://www.example.com/api/v1/all/limit/{limit}/offset/{offset}'
// this is stored as a string inside a config file
then $limit = 10; $offset = 0;
I currently use the following preg_replace
to replace the given URL and transform into an effective URL:
$url = preg_replace('/\{([A-Z, a-z]+)\}/e', "$$1", $url);
The effective string is now:
It works, however, I had to dig deep into figuring out the pattern and $$1
part so there goes readability.
My questions:
Is there anything else out there that someone can think of that can be as good as the above code?
I could use a
str_replace
with 2 arrays and do a replacement of the variables - it might be cleaner but it maybe slower. Would anyone advise replacing that theory instead of this? If so, why?The number of variables could grow - currently doing this it will capture all $variable there is within that scope - so any suggestion would need to keep in mind that limit/offset will not be the only limited variables that will be incoming. ie:
$url = 'http://www.example.com/api/v1/all/id/{id}/limit/{limit}/offset/{offset}'
$url = 'http://www.example.com/api/v1/all/relatedId/{relatedId}/limit/{limit}/offset/{offset}'
$url = 'http://www.example.com/api/v1/all/id/{id}/limit/{limit}/offset/{offset}'
FINAL ANSWER
I am giving the accepted jsanc623.
It was a toss up between vsprintf() (a variant of sprintf as Alex L suggested) where you can specify an array of arguments to be plugged in or str_replace with the new edit.
The reason why I am accepting jsanc623's answer is that despite vsprintf being faster and enabling me to plug in X variables as I see fit I loose the integrity of the URL if I start replacing the variables to be %d instead (ie: readability). I also loose validation (what if I program it wrong and swap limit and offset or any N variables' sequence wrong). Therefore with the speed gain and flexibility retained str_replace is the most viable solution until the N variable increases to the point where preg_replace would be most optimal.
$url = 'http://www.example.com/api/v1/all/relatedId/{relatedId}/limit/{limit}/offset/{offset}'