我使用的是strstr( $ip, ':') === false ? $ip : strstr( $ip, ':', true);,但这当然不适用于ipv6,所以我想知道是否有一种更简洁的方法来检查是否提供了端口,并在PHP中删除它。
因此,对于:
192.168.0.1
192.168.0.1:3233
2001:569:be89:6200:5da6:745a:84fe:d899:3423我得到了:
192.168.0.1
192.168.0.1
2001:569:be89:6200:5da6:745a:84fe:d899发布于 2021-03-26 02:02:04
<?php
$arr = [
'192.168.0.1',
'192.168.0.1:3233',
'2001:569:be89:6200:5da6:745a:84fe:d899:3423',
'[2001:db8::1]:8080'
];
print_r(array_map(fn($v) => parse_url('http://'.$v, PHP_URL_HOST), $arr));结果将是所有主机,没有端口
Array
(
[0] => 192.168.0.1
[1] => 192.168.0.1
[2] => 2001:569:be89:6200:5da6:745a:84fe:d899
[3] => [2001:db8::1]
)发布于 2021-03-27 04:44:47
实际上,我最终使用了这个,这不是最优雅的解决方案,但它是有效的。
if ( strpos( $ip, ':') !== false ) {
// ipv6
if( count( explode(':', $ip ) ) > 2 && strpos( $ip, '[') !== false )
$ip = parse_url('http://'.$ip, PHP_URL_HOST);
elseif( count( explode(':', $ip ) ) === 2 )
$ip = strstr( $ip, ':', true );
}请注意,the answer from @lawrence-cherone不适用于IP 2001:569:be89:6200:8936:7907:fcf1:961b。
https://stackoverflow.com/questions/66804903
复制相似问题