Home  >  Article  >  Backend Development  >  Discuss how to implement PHP to determine whether a string is IP_PHP tutorial

Discuss how to implement PHP to determine whether a string is IP_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:31:082245browse

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.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446235.htmlTechArticleIn some query websites and search engines, it is often used to determine whether a certain string is a standard IP address, such as in Searching for an IP address in Baidu will display the IP information, which does not meet the standards...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn