Jump to content

Recommended Posts

I have a database full of strings which are basically URL's with ports, so by default my strings look like:

 

http://example.com:1234/

http://example2.com:3030/

http://example.com:9876/

http://example.com:5432/

 

What I am looking for is a way to separate the host from the post so the output would be something like:

 

Host: example.com

Port: 1234

 

Note: I once need to check one string at a time, so what I am after is something like:

 

$string =  "http://example.com:1234/";

 

And the result would be something like:

 

$host (would be example.com without http://)

$port (would be the port without ending /)

 

Any help would be great :)

 

Thanks for your time reasing this.

 

Link to comment
https://forums.phpfreaks.com/topic/246703-splitting-string-into-two-parts/
Share on other sites

You can do this easily with explode (and rtrim() to remove the trialling slash):

 

list($host, $port) = explode(':', rtrim($string, '/'));

 

Edit

 

Didn't spot the "without http://" comment, use this instead:

 

$string = str_replace('http://', '', $string);
$string = rtrim($string, '/');

list($host, $port) = explode(':', $string);

Thanks for your replies.

 

@adam, The $host part works fine and returns the host, but $port doesn't return anything for some reason (using your edited code). Any idea what might cause the port part to stay empty?

 

Edit, I just noticed that my sql query returned a sample record where no port was existing - sorry about this false statement - the code is fine as posted - Thanks!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.