1

Is there any way to do this, without using the error control operator on @preg_match ? :)

Because PHP requires that patterns are wrapped between a character, I was thinking to do it this way:

  1. Get the first character.
  2. Find the last occurence of this character in the string with:

    $rpos = strrpos($string, $string[0]);
    
  3. Get the modifier list:

    $mods = substr($rpos, strlen($string));
    
  4. Find out if there are any invalid modifiers in this list. If there are return false, otherwise regex appears to be valid.

How reliable is this solution? Are there any better ones?

Anna K.
  • 1,887
  • 6
  • 26
  • 38
  • Can you give an example string where it would fail? – Anna K. Mar 26 '13 at 19:54
  • 1
    You could use filter_var() with the option FILTER_VALIDATE_REGEXP – aurbano Mar 26 '13 at 19:54
  • AnnaK: `/(/` would pass your test, but isn't a valid regex because it contains an unmatched parenthesis. Also keep in mind that some regexes may be valid, but will consume an unreasonable amount of time or memory to run. –  Mar 26 '13 at 19:55
  • 1
    does FILTER_VALIDATE_REGEXP really work? – Anna K. Mar 26 '13 at 19:56
  • No, FILTER_VALIDATE_REGEXP = "Validates value against regexp, a Perl-compatible regular expression.". Unless suggestion was to use the regex in Wouter J's answer with the `filter_var` method. – ficuscr Mar 26 '13 at 20:03

2 Answers2

2

I'm always using this function in the Symfony2 Finder component:

if (preg_match('/^(.{3,}?)([imsxuADU]*)$/', $expr, $m)) {
    $start = substr($m[1], 0, 1);
    $end   = substr($m[1], -1);

    if (($start === $end && !preg_match('/[*?[:alnum:] \\\\]/', $start)) || ($start === '{' && $end === '}')) {
        // It's a regex!
    }
}
Wouter J
  • 41,455
  • 15
  • 107
  • 112
  • nice:D I think that this does the same thing as I suggested, but also checks for minimum characters – Anna K. Mar 26 '13 at 20:05
1

In the commets it is already described in the short way. But you can check if the regex is okay by using the filter_var method

$string = "String to match";

if (filter_var($string, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" =>  "/abc/")))) {
    echo "Regex is OK";
} else {
    echo "Regex not okay";
}
Wouter J
  • 41,455
  • 15
  • 107
  • 112
Benz
  • 2,317
  • 12
  • 19
  • `Warning: filter_var() [function.filter-var]: 'regexp' option missing in...` – Anna K. Mar 26 '13 at 20:08
  • The second piece of PHP is the code to use. The filter_var setup that I first used is only available with other filters (like FILTER_VALIDATE_INT). – Benz Mar 26 '13 at 20:17