I would like to add [ and ] in my validation Regex that already accept all numeric, underscore, period and alphanumeric character.
Here is the regex working:
$regex = “^[._a-zA-Z0-9-]*$”;
But when I try :
$regex = "^[.\\[\\]_a-zA-Z0-9-]*$";
or
$regex = "^[.\[\]_a-zA-Z0-9-]*$";
It doesn’t work (I have read to double escape in PHP for bracket but it doesn’t work!
I use eregi.
Any idea?
Test :
<?php
//$regex = "^[_a-zA-Z0-9-]*$";
$regex = "^[.\\[\\]_a-zA-Z0-9-]*$";
echo("1".(eregi($regex, "patrick")?"True":"False"));//Should return True
echo("<br>");
echo("2".(eregi($regex, "p@trick")?"True":"False"));
echo("<br>");
echo("3".(eregi($regex, "pat rick")?"True":"False"));
echo("<br>");
echo("4".(eregi($regex, "patr'ick")?"True":"False"));
echo("<br>");
echo("5".(eregi($regex, "pAtr'ick")?"True":"False"));
echo("<br>");
echo("6".(eregi($regex, "pAtr_ick")?"True":"False"));//Should return True
echo("<br>");
echo("7".(eregi($regex, "pA-tr_ick")?"True":"False"));//Should return True
echo("<br>");
echo("8".(eregi($regex, "pAaAta atrack")?"True":"False"));
echo("<br>");
echo("9".(eregi($regex, "pA%k")?"True":"False"));
echo("<br>");
echo("10".(eregi($regex, "patrick.second")?"True":"False")); //Should return True
echo("<br>");
echo("11".(eregi($regex, "[Pat]Rick")?"True":"False"));//Should return True
echo("<br>");
?>
The former one should work. You need to use two backslashes: one for the regular expression escape and one for the string escape. Just see how it gets evaluated:
And that’s exactly what you need.
Edit Use
preg_matchinstead:I don’t know why this regular expression doesn’t work with
eregi, but it does withpreg_match. Futhermore the POSIX ERE functions are deprecated and will be removed by PHP 6 in favor of the PCRE functions. Note that PCRE regular expressions use delimiters to enclose the regular expression and separate it from the modifiers.