PHP - 检查字符串是否包含IP地址

时间:2014-06-04 15:50:32

标签: php regex dns

我有一个这样的字符串:

“(01:42 PM)76.124.231.190威廉:你好?”

我需要一个正则表达式来删除这样的IP地址:

preg_replace($regex, "", "(01:42 PM)76.124.231.190 William: Hello?")
// --> "(01:42 PM) William: Hello?"

我见过这个:Regex to match an IP address,但检查字符串是否是一个IP,而不是它是否包含它。

此外,它不一定非常完美,999.99.999.999可以简化。

3 个答案:

答案 0 :(得分:1)

最简单的是,这个正则表达式应该可行。

preg_replace('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', "", "(01:42 PM)76.124.231.190 William: Hello?")

答案 1 :(得分:0)

如果你在IP之前使用相同的字符串长度,那么每次你可以在php中使用子字符串并选择ip地址。只需使用substr

http://www.php.net/manual/en/function.substr.php

答案 2 :(得分:-1)

好像你试图从字符串中提取特定的IP。你不需要正则表达式。

使用str_replace

可以轻松完成此操作
$myStringWithIP = '(01:42 PM)76.124.231.190 William: Hello?';
str_replace('76.124.231.190', '', $myStringWithIP);

#$myStringWithIP now equals '(01:42 PM) William: Hello?'

我希望这有帮助!