RE: Regex help

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



kjohnson@xxxxxxxxxxx wrote:
> OK, this is off-topic like every other "regex help" post, but I know
> some of you enjoy these puzzles :)

This isn't an exam question, is it? ;)

> I need a validation regex that will "pass" a string. The string can
> be no longer than some maximum length, and it can contain any
> characters except two consecutive ampersands (&) anywhere in the
> string.
>
> I'm stumped - ideas?

Yup, use this perl regex:

/^(?:(&)(?!&)|[^&]){1,5}$/

Where 5 above is the maximum length of the string.  You can change this to
any positive value and the regex will still work.  Basically it says "look
for 1 to 5 single characters where each either isn't an ampersand, or IS an
ampersand but isn't immediately followed by an ampersand".  The (?!&) is a
zero-width negative look-ahead assertion which is like other assertions such
as "\b" that don't eat up the portions of the string that they match.

Sample code, tested:

$maxLen = 5;

$testStrings = array(
  'a',
  '&g',
  'd&f',
  'adfdf',
  'adfsdfff',
  '&f&f&',
  '&&dfds&',
  'dsdf&',
  'd&&df',
  'dff&&'
);

foreach ($testStrings as $string) {
  if (preg_match("/^(?:(&)(?!&)|[^&]){1,$maxLen}$/", $string)) {
    print "$string matches.\n";
  } else {
    print "$string does not match.\n";
  }
}

Hope this helps you (pass your exam? ;) )

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux