I have a list of absolute URLs. I need to make sure that they all have trailing slashes, as applicable. So:
I'm guessing I need to use regex, but matching URLs are a pain. Was hoping for an easier solution. Ideas?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With