duanhui5344 2011-06-09 15:53
浏览 87
已采纳

PHP - 将ereg转换为preg_match

I have a script I have used for quite a while that validates UK postcodes, issue I have is one part of the function uses ereg rather than preg_match.

Could someone point me in the right direction with the below please? I have added delimiters but not getting the same results as I was before.

$alpha1 = "[abcdefghijklmnoprstuwyz]";
$alpha2 = "[abcdefghklmnopqrstuvwxy]";
$alpha3 = "[abcdefghjkstuw]";
$alpha4 = "[abehmnprvwxy]";
$alpha5 = "[abdefghjlnpqrstuwxyz]";

// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
$pcexp[0] = '/^(' . $alpha1 . '{1}' . $alpha2 . '{0,1}[0-9]{1,2})([0-9]{1}' . $alpha5 . '{2})$/';

// Expression for postcodes: ANA NAA
$pcexp[1] = '/^(' . $alpha1 . '{1}[0-9]{1}' . $alpha3 . '{1})([0-9]{1}' . $alpha5 . '{2})$/';

// Expression for postcodes: AANA NAA
$pcexp[2] = '/^(' . $alpha1 . '{1}' . $alpha2 . '[0-9]{1}' . $alpha4 . ')([0-9]{1}' . $alpha5 . '{2})$/';

// Exception for the special postcode GIR 0AA
$pcexp[3] = '/^(gir)(0aa)$/';

// Standard BFPO numbers
$pcexp[4] = '/^(bfpo)([0-9]{1,4})$/';

// c/o BFPO numbers
$pcexp[5] = '/^(bfpo)(c\/o[0-9]{1,3})$/';
  • 写回答

1条回答 默认 最新

  • dongsi2317 2011-06-09 15:57
    关注

    At a first glance, everything looks OK, but you need to make the regex case-insensitive by adding an i after the closing delimiter:

    $pcexp[4] = '/^(bfpo)([0-9]{1,4})$/i';
    

    and so on.

    Your regexes don't allow for spaces between the parts of the postcode. Is this intentional? If not, add a \s* everywhere spaces are legal

    Also, you can drop all instances of {1} and replace each {0,1} with ?.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效