Jump to content

Splitting string into two parts


Mcod

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!

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.