Jump to content

Modify existing regex to support commas and spaces


solarisuser

Recommended Posts

This will allow a comma with spaces, or just spaces:

 

<pre>
<?php

$ips = array(
	'192.168.0.1, 192.168.0.2',
	'192.168.0.1 192.168.0.2',
	'192.168.0.1 192.168.0.2,',
	'192.168.0.1 192.168.0.2   '
);

foreach ($ips as $ip) {
	echo $ip, '<br>',
		preg_match('/^(??:\d{1,3}\.){3}\d{1,3}(?:\z|,?\s+))+\z/', $ip) ?
		'Matches' : 'Does not match', '<br>';
}

?>
</pre>

I'd like to modify the request. 

 

Using this regex:

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

 

I'd like to modify it to allow commas, followed by an additional IP, up to an unlimited amount of times, without having a comma at the end.

 

For example: 192.168.1.1,192.168.1.2,192.168.1.3          , or just 192.168.1.1

 

Thanks - its been a tough one for me to try and figure out!

Try this.. seams to work fine


<?php
$IPs = "192.168.1.1,192.168.1.2,192.168.1.3";
//$IPs = "192.168.1.1";

preg_match_all('/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/', $IPs, $result, PREG_PATTERN_ORDER);
$result = $result[0];

//print_r($result);
foreach($result as $IP)
{
echo "$IP<br />";
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.