简体   繁体   中英

Simple PHP regular expression question

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;
}

?>

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 :

简单:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM