Home >Backend Development >PHP Tutorial >Discuss how to implement PHP to determine whether a string is IP_PHP tutorial
In some query websites and search engines, it is often used to determine whether a certain string is a standard IP address. For example, searching for an IP address in Baidu will display the IP information. IP information will not be displayed for IP addresses that do not meet the standards. At this time, it is necessary to determine whether the string is a standard IP. The most common method is to use regular expressions to determine.
I searched for some regular rules for judging IP addresses on the Internet. They are all too simple. Some only judge that the IP field is not larger than 255. In fact, there are many things that need to be judged. For example, it can only be numbers and cannot be Negative numbers, and using "." to divide only 4 segments, etc.
It’s best that I compiled a function that I feel is perfect. The PHP code to determine whether a string is an IP is as follows:
<ol class="dp-xml"> <li class="alt"><span><span>function is_ip($gonten){ </span></span></li> <li> <span>$</span><span class="attribute">ip</span><span> = </span><span class="attribute-value">explode</span><span>(”.”,$gonten); </span> </li> <li class="alt"> <span>for($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">0</span><span>;$i</span><span class="tag"><</span><span class="tag-name">count</span><span>($ip);$i++) </span></li><li><span>{ </span></li><li class="alt"><span>if($ip[$i]</span><span class="tag">></span><span>255){ </span> </li> <li><span>return (0); </span></li> <li class="alt"><span>} </span></li> <li><span>} </span></li> <li class="alt"><span>return ereg(”^[0-9]{1,3}.<br>[0-9]{1,3}.[0-9]{1,3}.[0-9]<br>{1,3}$”,$gonten); </span></li> <li><span>} </span></li> </ol>
$gonten is the string to be queried. Use is_ip($gonten) to implement PHP to determine whether the string is IP and return FALSE and TRUE.