ds34222222 2010-02-14 17:52
浏览 72
已采纳

如何在PHP Regex类中使用方括号?

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>");
?>
  • 写回答

5条回答 默认 最新

  • douyi8732 2010-02-14 17:55
    关注

    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:

    echo "^[.\\[\\]_a-zA-Z0-9-]*$"; // => ^[.\[\]_a-zA-Z0-9-]*$
    

    And that’s exactly what you need.


    Edit    Use preg_match instead:

    preg_match("/^[.\\[\\]_a-zA-Z0-9-]*$/i", $str)
    

    I don’t know why this regular expression doesn’t work with eregi, but it does with preg_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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?