正则表达式只从文本中提取IPv4地址 [英] Regex to extract only IPv4 addresses from text
本文介绍了正则表达式只从文本中提取IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试从给定的示例输入中仅提取IP地址,但它会用它提取一些文本。这是我的代码:
I've tried to extract only IP addresses from the the given example input, but it extracts some text with it. Here's my code:
$spfreccord="v=spf1 include:amazonses.com include:nl2go.com include:smtproutes.com include:smtpout.com ip4:46.163.100.196 ip4:46.163.100.194 ip4:85.13.135.76 ~all";
$regexIpAddress = '/ip[4|6]:([\.\/0-9a-z\:]*)/';
preg_match($regexIpAddress, $spfreccord, $ip_match);
var_dump($ip_match);
我希望只匹配IPv4 IP地址 xxx.xxx。表中每列的xxx.xxx
,但看起来 $ regexIpAddress
不正确。
I'm looking to match only the IPv4 IP address xxx.xxx.xxx.xxx
in each column of the table, but it looks like that the $regexIpAddress
is not correct.
你能帮我找到正确的正则表达式来提取IPv4 IP地址吗?谢谢。
Can you please help me find the correct regex to extract only the IPv4 IP addresses? Thanks.
推荐答案
使用以下正则表达式:
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/
所以对此:
$spfreccord="v=spf1 include:amazonses.com include:nl2go.com include:smtproutes.com include:smtpout.com ip4:46.163.100.196 ip4:46.163.100.194 ip4:85.13.135.76 cidr class v=spf1 ip4:205.201.128.0/20 ip4:198.2.128.0/18 ~all";
$regexIpAddress = '/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?:\/\d{2})?/';
preg_match_all($regexIpAddress, $spfreccord, $ip_match);
var_dump($ip_match);
给予:
array(1) {
[0]=>
array(5) {
[0]=>
string(14) "46.163.100.196"
[1]=>
string(14) "46.163.100.194"
[2]=>
string(12) "85.13.135.76"
[3]=>
string(16) "205.201.128.0/20"
[4]=>
string(14) "198.2.128.0/18"
}
}
这篇关于正则表达式只从文本中提取IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文