I’m trying use preg_match in an IF statement and return false if a string contains some templated functions not allowed.
Here are some example templated functions allowed:
{function="nl2br($value.field_30)"}
{function="substr($value.field_30,0,250)"}
{function="addslashes($listing.photo.image_title)"}
{function="urlencode($listing.link)"}
{function="AdZone(1)"}
These are mixed in with html etc.
Now I’d like this preg_match statement to return true if regex matches the code format but didn’t contain one of the allowed function keywords:
if (preg_match('(({function=)(.+?)(nl2br|substr|addslashes|urlencode|AdZone)(.+?)\})',$string)) {
// found a function not allowed
} else {
// string contains only allowed functions or doesn't contain functions at all
}
Does anyone know how to do this?
Not quite sure what you’re trying here, but if I were to make a regexp that matched a list of words (or function names as the case may be), I’d do somthing like
The
$allowedarray makes it easier to add/remove allowed function names, and the regexp is stricter about the curly brackets, quotes and general syntax, which is probably a good idea.But first of all, flip the if..else branches, or use a
!.preg_matchis meant for, well, matching stuff in the string, not for matching stuff that isn’t in there. So you can’t really get it to returntruefor something that isn’t thereStill, as Álvaro mentioned, regexps probably aren’t the best way to go about this, and it is pretty risky to have functions exposed like that, no matter the rest of the code. If you just needed to match words it should work fine, but since it’s function calls with arbitrary arguments… well. I can’t really recommend it 🙂
Edit: First time around, I used
preg_quoteon the imploded string, but that of course just escapes the pipe characters, and then the pattern won’t work. So skippreg_quote, but then just be sure that function names don’t contain anything that might mess up the final pattern (e.g. run each function name throughpreg_quotebefore imploding the array)