HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Cleaner or better readability in URL composition

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readabilitybettercleanerurlcomposition

Problem

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:


http://www.example.com/api/v1/all/limit/10/offset/0

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:

$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}'

Solution

You could simplify to something such as:

$url = 'http://www.example.com/api/v1/all/limit/%d/offset/%d';

$newURL = sprintf($url, $limit, $offset);


We use sprintf() for this.

Update


e (PREG_REPLACE_EVAL)


Warning This feature has been DEPRECATED as of PHP 5.5.0. Relying on
this feature is highly discouraged.

Docs

Now I really suggest you find an alternative.

According to your update, you say the number of variables might grow. Could you explain (example code?) this more? If it "grows", then the issue may not be this part of the function, it may be the surrounding code that needs fixing.

Code Snippets

$url = 'http://www.example.com/api/v1/all/limit/%d/offset/%d';

$newURL = sprintf($url, $limit, $offset);

Context

StackExchange Code Review Q#57224, answer score: 4

Revisions (0)

No revisions yet.