Grab the IP port in a string

Asked

Viewed 180 times

0

With a problem here, I need to separate an IP string into two parts, between the address and the port.

Example:

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

Turn:

$string1 = 127.0.0.1;
$string2 = 7777;

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

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

Can someone help me?

  • if the problem is having the DB registered together and you are separating in the application, compensates to separate via SQL in 2 fields (direct in DB)

2 answers

7

You can use the parse_url:

Example:

<?php   

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

Exit

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

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

Mode of Use

echo $array_info1['host'];  
echo $array_info1['port'];

4

You can use PHP’s explode function.

This function basically works this way: you give as input a delimiter/separator and a string. The function will take the string which you have provided and will break at each node (abalizations), forming a array size n + 1, where n is the number of times the delimiter has been found in the string past tense.

To access the values of array, the indices of each element formed by the break of the string (the number of items in the array shall be equal to the number of times the demarcator 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: http://php.net/manual/en/function.explode.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.