Shorten code to loop through array?
Shorten code to loop through array?
(OP)
I'm checking my form fields for links to other websites, if I find more than two I mark as SPAM. Is there a way to simplify this code? Maybe put all of my form fields in an array and loop through it and just write the preg_match code once? I just don't know how to do it!
CODE --> php
if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['name'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['business'])) $points += 1; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['address'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['city'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['state'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['zip'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['day_phone'])) $points += 4; if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['evening_phone'])) if(preg_match("/\b(?:(?:https?|ftp|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$_POST['comments'])) $points += 1; // end score assignments
RE: Shorten code to loop through array?
Looks like having the same URL in two fields is a problem, but having a dozen URLs in one field is Ok. Is that really your intention ?
I would do it like this, counting for each URL the weight you assigned to the field where was found :
CODE --> PHP
Feherke.
feherke.github.io
RE: Shorten code to loop through array?
Anyway, this does look much cleaner. I see the reg expression is different than the one I used? Does yours not check for http:
Also can you explain the asterisk before the expression, I'm really trying to learn this.
Thanks and I will try this out.
RE: Shorten code to loop through array?
It does. https? means "http" followed by "s" repeated 0 or 1 times. So matches either "http" or "https".
No magic, just arithmetic multiplication.
I use preg_match_all() which returns the number of matches found.
So if $_POST['business'] contains "http://example.com/ is similar to http://example.net/, just like http://example.org/", then preg_match_all() returns 3, so $points gets incremented by the business field's weight of 1 multiplied with 3.
Feherke.
feherke.github.io
RE: Shorten code to loop through array?