Search code examples
phpsubstringip-addresshost

Exact an IP address out of a Host URL


I have a host = http://172.19.242.32:1234/

My goal is to grab the IP only = 172.19.242.32

I tried

$ip = trim($host,'http://');
$ip = str_replace("/", "",$ip);
$ip = explode(":",$ip);
$ip = $ip[0];

I got my IP as expected, but I can't do it this way anymore because it will mess up the IPv6 format.

What is the alternative way? Any suggestion?


Solution

  • Use parse_url(): You can ommit PHP_URL_HOST to return an array of all components.

    <?php
    $host = 'http://172.19.242.32:1234/';
    echo parse_url($host, PHP_URL_HOST);
    

    returns

    172.19.242.32
    

    https://eval.in/770497