How to match part of string inside array - PHP
Is there a way to match a part of a string within an array in PHP?
I would like to validate a user ip against allowed IPs. Therefore I have created an array with IPs and coresponding partner_id. This works, however I also want to allow an entire subnet and would therefore need to mach against part of the array. Is this possible?
This is my code:
# define partner IPs $partner_ips = array( '192.168.56.1' => 0, // dev '192.168.57.*' => 1 // office ips ); # test for partner IP and associate partner_id if found if (array_key_exists($_SERVER['REMOTE_ADDR'], $partner_ips)) $partner_id = $partner_ips[$_SERVER['REMOTE_ADDR']]; else $partner_id = false;
Thank you for any help on this.
Check the ip format first. Build two different arrays, one for full ip adresses and one for subnets. An example class (feel free to make it PSR-2 compliant, since you use PHP 5.6 you can also declare the two arrays as class constants instead of static variables):
You can use it like this:
You can use in_array for check if your string exist in array or not