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条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?