Home >Backend Development >PHP Tutorial >Code to obtain the physical address of a specified IP in PHP (regular expression)_PHP Tutorial
Building your own IP database takes up resources and is inconvenient to update. Why not use a ready-made IP query? Below I wrote a PHP code to obtain the IP physical address (there are certain flaws, please feel free to enlighten me)
"; <br>print_r($addrArray); <br>echo "< /pre>"; <br>?> <br></body> <br></html> <br> </div> <br>This code is used to visit http://www.ip138.com Then use regular expressions to intercept part of the content, where the regular expressions are written by yourself. <br><img src="http://www.bkjia.com/uploads/allimg/131016/13192H627-0.png" alt="Code to obtain the physical address of a specified IP in PHP (regular expression)_PHP Tutorial" ><br>It was okay at first, but the following processing results were garbled. If the string defined by $str (removing the identifier at the beginning and end of the string) is defined, there will be no garbled characters; and a separate " :" statement, you can achieve the phenomenon of no garbled characters, I don’t know why... <br><strong>Regular expression - Get the physical address of the specified IP (2) chinaz data <br></strong>Previous IP The result obtained was not very perfect. The reason was that the IP resolution of ip138 was not very detailed when dealing with foreign addresses, so I re-wrote the code using Chianz.com. <br><div class="codetitle"> <span style="CURSOR: pointer" onclick="doCopy('code40589')"><u>Copy code</u></span> The code is as follows:</div> <div class="codebody" id="code40589"> <br><!DOCTYPE html> <br><html lang="en"> ; <br><head> <br><title></title> <br><meta charset="UTF-8" /> <br><meta name="author" content=" " /> <br><meta name="keywords" content="" /> <br><meta name="description" content="" /> <br></head> <br><body> <br><?php <BR>$ipAddr = "4.4.44.4"; <BR>$ipChinazAddr = "http://tool.chinaz.com/IP/?IP=".$ipAddr ; <BR>$contents = file_get_contents($ipChinazAddr); <BR>$pattern = "/==>>.+</strong><br />/"; <br>$string = $ contents; <br>preg_match_all($pattern,$string,$addrArray); <br>$num = count($addrArray[0]); <br>$pattern = "/(==>>).+ (==>>s)/"; <br>for($i = 0;$i<$num;$i++){ <br>$addrArray[0][$i] = preg_replace($pattern, "",$addrArray[0][$i]); <br>} <br>echo "<pre class="brush:php;toolbar:false">"; <br>print_r($addrArray); <br>echo "";
The above are two codes I wrote to obtain the IP physical address. As a beginner, it is quite interesting to write simple codes when I have nothing to do. But after all, I am a beginner and cannot pay more attention to issues such as security, space utilization, time efficiency, etc. I hope you will leave your footprints. Thanks, brother