A page I’ve made allows users to submit IP’s (All are IPv4, not IPv6) with %’s as wildcards (e.g. 192.168.1.%). They can also submit full IP’s without wildcards. The IP’s are posted via a regular HTML form input, so something like <input name=\"ip\" maxlength=\"15\"/>.
Essentially, I just need to check that IP’s only contain numbers, dots, and percent signs (two at most). I’m not really concerned with people putting in numbers that are greater than 255, but I don’t want them to be able to put more than three numbers per every dot.
I don’t know regex much at all, so I don’t even know where to begin. I know that [0-9] would only allow numbers 0-9, but that’s probably not going to help much. Should I be splitting the $_POST[‘ip’] variable into parts using dots as the delimiter, then running regex stuff on each part? It’s probably more efficient just to run it all at once.
While you could do this with a Regular Expression, I believe it would be complex and a more straightforward solution would be a combination of String functions and
filter_var().Pseudo Code
substr_count()the wildcards to ensure max of 2str_replace()wildcards with a safe digit, say50filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)If any of these fail, you have a bad IP. In the interest of teaching you to fish, I’ll leave the code up to you.