Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: how to add trailing slash to absolute URL

Tags:

regex

url

php

I have a list of absolute URLs. I need to make sure that they all have trailing slashes, as applicable. So:

  • http://www.domain.com/ <-- does not need a trailing slash
  • http://www.domain.com <-- needs a trailing slash
  • http://www.domain.com/index.php <-- does not need a trailing slash
  • http://www.domain.com/?message=hello <-- does not need a trailing slash

I'm guessing I need to use regex, but matching URLs are a pain. Was hoping for an easier solution. Ideas?

like image 369
StackOverflowNewbie Avatar asked Mar 27 '11 08:03

StackOverflowNewbie


2 Answers

For this very specific problem, not using a regex at all might be an option as well. If your list is long (several thousand URLs) and time is of any concern, you could choose to hand-code this very simple manipulation.

This will do the same:

$str .= (substr($str, -1) == '/' ? '' : '/');

It is of course not nearly as elegant or flexible as a regular expression, but it avoids the overhead of parsing the regular expression string and it will run as fast as PHP is able to do it.
It is arguably less readable than the regex, though this depends on how comfortable the reader is with regex syntax (some people might acually find it more readable).

It will certainly not check that the string is really a well-formed URL (such as e.g. zerkms' regex), but you already know that your strings are URLs anyway, so that is a bit redundant.

Though, if your list is something like 10 or 20 URLs, forget this post. Use a regex, the difference will be zero.

like image 81
Damon Avatar answered Sep 17 '22 18:09

Damon


Rather than doing this using regex, you could use parse_url() to do this. For example:

$url = parse_url("http://www.example.com/ab/abc.html?a=b#xyz");
if(!isset($url['path'])) $url['path'] = '/';
$surl = $url['scheme']."://".$url['host'].$url['path'].'?'.$url['query'].'#'.$url['fragment'];
echo $surl;
like image 26
asleepysamurai Avatar answered Sep 17 '22 18:09

asleepysamurai