0

I have been finding myself doing URLs like this:

$link = base_url('post') . '/' . $post_id . '/' . $slug . '/page/' . $page_num;

To form http://example.com/post/10/some-post-name/page/1

Needless to say, it's pretty messy, but I can't think of an alternative? Is there a better way write links with variables in it?

I am using Codeigniter as a framework if there is a solution involving it.

4
  • 2
    You could use double-quotes ("")? Dec 5, 2012 at 22:13
  • 1
    Sprintf php.net/manual/en/function.sprintf.php is good
    – Raekye
    Dec 5, 2012 at 22:13
  • Double quotes look the best in my opinion, and are the fastest of all alternatives....only your code beats double quotes in speed. stackoverflow.com/questions/3316060/… Dec 5, 2012 at 23:23
  • heh - its actually easier to read then any of the posted alternatives - and its the fastest. but yes to using site_url(), that was a good catch -- and double quotes would read a little easier.
    – cartalot
    Dec 6, 2012 at 20:22

4 Answers 4

3

You have a few ways:

First, via sprintf:

sprintf('%s/%s/%s/page/%s', base_url('post'), $post_id, $slug, $page_num);

Or via an array implode:

implode('/', array(base_url('post'), $post_id, $slug, 'page', $page_num));

Or if you put all your values into variables, you can take advantage of string interpolation.

$url = ...;
...
"$url/$post_id/$slug/page/$page_num";

The last one is longer when you take into account the variable assignment block, but it combines succintness with readability.

1
2

Use sprintf:

$link = sprintf('%s/%d/%s/page/%d', base_url('post'), $post_id, $slug, $page_num);
1

You could do something like this:

$link = site_url("post/{$post_id}/{$slug}/page/{$page_num}");

You really should be using site_url() instead of base_url() for CI links. base_url() is meant for non-CI assets, like images and css.

site_url() will point to the correct front controller path, so you can update your configuration at will, and everything using that to build paths will update accordingly.

I revised my answer. Use the curly brace notation and avoid using extra functions. You can pass an array of arguments to the function, like so:

$link = site_url(array('post', $post_id, $slug, 'page', $page_num));

But working with arrays is slower. This can be useful if you need to dynamically build the url, though.

0

You could do it the old fashioned way with a function!

function buildlink($base_url,$post_id,$slug,$page_num)
{
  return $base_url . '/' . $post_id . '/' . $slug . '/page/' . $page_num;
}

call it like this

$link = buildlink(base_url('post') ,$post_id, $slug ,$page_num);

but maybe i'm missing something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.