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_replacewith 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:
$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}'
[A-Z, a-z], you really mean[A-Za-z]. The former will match characters as well as commas and spaces. In general, recall thata-dis short forabcdin character classes, so[A-Da-d]becomes[ABCDabcd], which is right, while[A-D, a-d]becomes[ABCD, abcd], which is probably wrong. \$\endgroup\$