RE: [PHP] Sterilizing regexp



-----Original Message-----
From: Frank Stanovcak [mailto:blindspotpro@xxxxxxxxxxx]
Sent: Tuesday, September 30, 2008 12:45 PM
To: php-general@xxxxxxxxxxxxx
Subject: [PHP] Sterilizing regexp

A while ago I asked a question and got a few answers, so I thought I
would
toss this out there as a follow up. I'm going to be using this to
return
filtered regexp values for a user interface.

I haven't had a chance to enter this into my code yet, so if anyone
sees
something wrong please hammer away, otherwise I hope it helps save
some
one
some time.

function regexp_sanitize($string,$regexp) {
if(isarray($string)) {
foreach($string as $key => $value) {
$count = preg_match($regexp,$value,$matches) {
if($count != 1) {
$result[$key] = FALSE;
} else {

I have a problem with this part right here:

foreach($matches as $toss => $matchval) {
$result[$key] = $matchval;
};

If there are multiple matches, you will only wind up with the last match
in $result[$key].

};
};
} else {
$count = preg_match($regexp,$string,$matches);
if($count != 1) {
$result = FALSE;
} else {
$result = $matches[0];
};
};
return($result);
};

Also, I believe you want preg_match_all() if you're going to be wanting
to grab the "matches." Note: MATCH and CAPTURE GROUP are not the same
thing. The $matches array you're working with from preg_match() should
contain the entire string that was matched in the first array slot and
subsequent capture groups--(.*?) for instance--in the remaining array
slots. preg_match_all() can be used to find multiple MATCHEs (perhaps
each with multiple CAPTURE GROUPs) if there are more than one in the
string being traversed.

HTH,


Todd Boyd
Web Programmer
.


Quantcast