Catch the IP port in a string

0

With a problem here, I need to separate a two-part IP string between the address and the port.

Example:

$string = 127.0.0.1:7777;
$string = px01.carbonhost.com.br:7786

Turn around:

$string1 = 127.0.0.1;
$string2 = 7777;

$string1 = px01.carbonhost.com.br;
$string2 = 7786;

This would be the easiest way for me, the other solution would be to have the user put the IP and Port separately, the problem is that many have already registered the IP with the port.

Can anyone help me?

    
asked by anonymous 27.05.2016 / 04:35

2 answers

7

You can use parse_url :

Example:

<?php   

    $array_info1 = (parse_url("127.0.0.1:7777"));
    $array_info2 = (parse_url("px01.carbonhost.com.br:7786"));

Output

array(2) { ["host"]=> string(9) "127.0.0.1" ["port"]=> int(7777) } 

array(2) { ["host"]=> string(22) "px01.carbonhost.com.br" ["port"]=> int(7786) }

How to Use

echo $array_info1['host'];  
echo $array_info1['port'];
    
27.05.2016 / 05:35
4

You can use the explode PHP function.

This function basically works this way: you give input a delimiter / separator and a string . The function will take the string that you provided and break it into each node, forming a array of size n + 1 , where n is the number of times that the delimiter was found in the last string . To access the values of the array , you must use the indexes of each element formed by breaking the string (the number of elements in the array in> will be equal to the number of times the path is found):

<?php

$input = '127.0.0.1:7777';

$ip = explode(':', $input);

$num_ip = $ip[0];
$porta = $ip[1];

echo 'Número IP: ' . $num_ip . '<br>' . 'Porta: ' . $porta;

References:

  

explode: link

    
27.05.2016 / 05:24