RE: [PHP] Regex help
| From: | Michael Sims | Date: | Sat, 29 Jan 2005 14:58:58 +0000 |
| Subject: | RE: [PHP] Regex help | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-207681@lists.php.net to get a copy of this message | ||
kjohnson@zootweb.com 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? ;) )