search
HomeBackend DevelopmentPHP TutorialRegular expression expression matching IP (recommended)

Here I will give you a detailed explanation of a regular expression that matches IP addresses.

Knowledge about regular expressions will be mentioned in the detailed explanation.

Before explaining, let me first introduce to you the rules for generating IP addresses.

The IP address is composed of a 32-digit binary number converted into a string of four decimal numbers.

How to convert? Explained below:

Binary: 111111111111111111111111111111

divided into four parts: 11111111.11111111.11111111.11111111

Conversion: 2^7+2^ 6+2^5+2^4+ 2^3+2^2+2^1+2^0=255

Convert to decimal range: 0~255.0~255.0~255.0~255

This is the range of the IP address.

Based on the rules and range of IP generation, we can use regular expressions to match the IP address, but how to match? Everyone has their own method, here I will explain my approach.

Based on the string rules of the IP address, I divided the expression matching the IP address into two parts to consider.

The first part: Match 3 0~255. (Note the dot at the end)

The second part: Match the last number 0~255

In other words, First match the string 0~255. (note the dot at the end), then repeat the match 3 times, and then match the last number part 0~255. This is my idea of ​​matching IP addresses.

First of all, I would like to mention that there is no way to do numerical operations with regular expressions, so we cannot use numerical operations to filter out the numerical range of IP. Since there is no way to filter out the numerical range of IP using number operations, what other methods should we use to filter this numerical range? My idea is to discuss in groups, and then merge these groups to form a numerical range of IP.

① Assuming that the IP number is in the hundreds digit, then based on the IP number range, we can draw the following situations. Assuming that the first number is 1, then the range of this number is 1[0-9][0-9]. This should not be difficult to understand, so I won’t explain it.

②. Assuming that the first number is 2, then according to the range rules of IP numbers, there are two situations here. Why? Think about it, the maximum number is 255. When the tens digit is 5, the single digit can only be 5 at most, right? And when the tens digit is 0 to 4, the ones digit can be any number, right?

So, the two situations here are:

A, 2[0-4][0-9]

B, 25[0-5]

③. After analyzing the hundreds digit situation, the next step is the tens digit situation. If it is a tens digit, then the first number in front of the tens digit cannot be zero, right?

So the ten-digit situation can be: [1-9][0-9]

④. The rest is the single-digit situation. The single-digit situation, Everyone should easily come to the conclusion, which is: [0-9].

After analyzing the four situations, we came to the conclusion that the range grouping of IP numbers is:

   1[0-9][0-9]

   2[0- 4][0-9]

25[0-5]

## How to express the above grouping using regular expressions? It's very simple, just use the regular or symbol | and the grouping symbol (), so the above grouping regular expression is:

(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9])

At this point, the matching range regular expression for numbers has been written. So according to my previous ideas: The first part: Match 3 0~255. (note the dot at the end)

The second part: Match the last number 0~255

Let’s match The first part of the IP address, the regular expression is as follows:

(1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)

I added a dot after each number to match 0~255. (Pay attention to the dot at the end)

Then How to repeat the match three times? It's very simple. We just need to treat these five groups as a whole and repeat the matching three times. The regular expression is as follows:

((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9])\.)){3}

The first part has been matched. The next step is to splice the numbers in the second part. , the numerical part has been written very clearly above, so I won’t explain it anymore. The following is the complete regular expression:

((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))

      写到这里,正则匹配IP的表达式已经出来了,不过,这并不是最终的匹配IP的正则表达式,为什么呢?很简单,正则表达式会对每一个分组都进行捕获匹配,上面把匹配IP分成了那么多分组,而每一个分组的内容都会被正则所捕获,那上面不知道已经捕获多少IP了,呵呵,那么怎么去掉分组的内容呢?很简单,用这个符号?:

      ?:符号放在()圆括号里面,是捕获分组,但不捕获正则表达式的内容的意思。那么,我们把它放到每一个分组里面去,不就去掉了分组的内容了吗?所以,我们还要给每个分组加上?:,加上后正则如下:

(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))

    即使到这里,还是没有把IP地址匹配出来,我们还要用^和$来限制字符串的开头和结尾,所以,最后的匹配IP地址的正则表达式是:

^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$

   

    这就是我匹配IP地址最完整的正则表达式,大家可以借鉴一下,有什么bug还望读者提出,免得误导其他读者。

    上面的正则表达式的()括号都是成对出现的,假如有不成对出现,请读者自己添加一下,可能是我漏写了。

    下面是我的测试:

<?php
$pattern = &#39;/^(?:(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:1[0-9][0-9]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:2[0-5][0-5])|(?:25[0-5])|(?:1[0-9][0-9])|(?:[1-9][0-9])|(?:[0-9]))$/&#39;;
//正则匹配ip地址
$ip     = &#39;254.21.0.198&#39;;
preg_match($pattern,$ip,$out);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($out);
$ip     = &#39;255.777.0.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;07.25.8.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;1207.25.8.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;qq107.25.8.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;\.\.\.107.25.8.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;\.\.\.  7.25.8.198&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;107.25.8.19822vvv&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;107.25.r8.1982&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;107.225.8.19&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;225.225.225.225&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;0.0.0.0&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;00.0.0.0&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;0.202.1.0&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;0.202.1.226&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$ip     = &#39;249.202.1.0&#39;;
preg_match($pattern,$ip,$out);
print_r($out);
$s=&#39;&#39;;
for($i=0;$i<32;$i++){
  $s .= &#39;1&#39;;
}
echo $s;
echo strlen($s);

更多正则表达式匹配IP的表达式(推荐)相关文章请关注PHP中文网!


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft