1

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
code-8
  • 54,650
  • 106
  • 352
  • 604

3 Answers3

4

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

alistaircol
  • 1,433
  • 12
  • 22
1
$url="http://172.19.242.32:1234/";
$regexIpAddress = '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/';        
preg_match_all($regexIpAddress, $url, $ip_match);
var_dump($ip_match[0]);

This reg expression match function will extract ip address from any string.

Nick Jang
  • 239
  • 4
  • 3
-2

The right way would be $_SERVER['SERVER_ADDR'] I think? It should return just the IP

junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33