Jump to content

[SOLVED] strip URL


lesmith

Recommended Posts

Hi chaps.

 

I already have got a working preg_replace but I am sure it can be written alot better.

 

It basically takes a url and strips http://www.

 

Here is my code.

 

$domain = "http://www.domain.com/";
$patterns[0] = '/\//';
$patterns[1] = '/http:/';
$patterns[2] = '/www./';
$replacements[0] = '';
$replacements[1] = '';
$replacements[2] = '';

echo preg_replace($patterns, $replacements, $domain);

 

This works fine but I am wondering if it can be improved upon.

 

Thank you if you can advice.

Link to comment
https://forums.phpfreaks.com/topic/142827-solved-strip-url/
Share on other sites

There's no reason why all of that can't be combined:

 

$domain = "http://www.domain.com/";

$pattern = "~http://www\.~";
$replacement = "";
echo preg_replace($pattern, $replacement, $domain);

 

And actually, if that is the extent of your $domain string (the only thing in it will be the url), you can just use substr, as it is much faster:

 

$domain = "http://www.domain.com/";

echo substr($domain, 11);

Link to comment
https://forums.phpfreaks.com/topic/142827-solved-strip-url/#findComment-748705
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.