tags:

views:

49

answers:

2

What's the most efficient preg_match regular expression for the following:

  1. The regular expression must match a certain string (case insensitive)
  2. Can be followed by [ or ; and then something else

These are the test cases for "foo":

  • foo --> good
  • food --> bad
  • foo; --> bad, need something after ;
  • FOO;bar --> good
  • foo[bar] --> good
  • foo[ --> bad, need something after ]
  • fOo[bar]1;2;3 --> good

This is my test code:

<?php

$tests = array();
$tests[] = 'foo';
$tests[] = 'food';
$tests[] = 'foo;';
$tests[] = 'FOO;bar';
$tests[] = 'foo[bar]';
$tests[] = 'foo[';
$tests[] = 'foo[]';
$tests[] = 'fOo[bar]1;2;3';

foreach ($tests as $test)
{
    echo $test, ' --> ';
    $found = preg_match('REGULAR EXPRESSION HERE', $test);
    if ($found === false || $found < 1)
        echo 'bad';
    else
        echo 'ok';
    echo '<br>', PHP_EOL;
}

?>
+2  A: 

You can try this regex :

/foo(;.+?|\[.+?\].*?)*$/i

If your bracket doesn't need to be closed :

/foo([;\[].+?)*$/i

If your bracket or semicolon must not be the last part of your expression :

/foo([;\[][^;\[]+)*$/i

All passed the tests with Regex planet.


Resources :

Colin Hebert
@Colin HEBERT They aren't working. "foo;" and "foo[" are considered valid...
Activist
@Activist, It's strange, can you show your code and the regex you used ?
Colin Hebert
@Colin HEBERT Added test code to OP. Just change "REGULAR EXPRESSION HERE" with the tested regexp. None of your 3 match my expected results.
Activist
Did you escaped the \ before you put it into the string ? You should have this : `$returnValue = preg_match('/foo(;.+?|\\\[.+?\\\].*?)*$/i', 'foo;');`
Colin Hebert
@Colin HEBERT No, escaping (doubling) the \ dosen't help...
Activist
http://ideone.com/9UeuC ... It worked even without the \ escaping.
Colin Hebert
@Colin HEBERT Yes I know but still foo; and foo[ are labeled as bad while they are ok...
Activist
Hum, from your first post : "foo; --> bad, need something after ;" and "foo[ --> bad, need something after ]"
Colin Hebert
@Colin HEBERT LOL you are right sorry I'm a little bit sleepy right now I guess :)
Activist
+2  A: 

Simple:

/foo($|[[;].)/i
unbeli