douji1999 2011-07-22 16:21
浏览 60
已采纳

需要有关URL正则表达式的帮助

Was just parsing urls of the type http://sitename.com/catid/300/, http://sitename.com/catid/341/ etc etc

wherein the parameter after the catid (300,341) are only integers. When I use the following condition in .htaccess, it works fine

 RewriteRule ^(abc|def|hij|klm)/([0-9]+)/$ /index3.php?catid=$1&postid=$2 [L]

but when a php regex match function,like preg_match, it returns 1 for alphanumeric numbers too

 eg: echo preg_match('([0-9]+)','a123'); or echo preg_match('([0-9]+)',a123);

They both return 1 ()true. I dont know why it matches alphanumerics. I want it to match only numbers.

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dpnv33177 2011-07-22 16:25
    关注

    Without anchors, it will match the numbers regardless of what comes before or after them. Try it with anchors:

    /^([0-9]+)$/
    

    If you don't need to capture, try this:

    /^[0-9]+$/
    

    Results:

    php > echo preg_match('([0-9]+)','a123');
    1
    php > echo preg_match('/^[0-9]+$/','a123');
    0
    php > echo preg_match('/^[0-9]+$/',0.65);
    0
    php > echo preg_match('/^[0-9]+$/',666);
    1
    

    Regular expressions are not always the answer. If you are just checking for a number, try is_numeric. If you just want an integer, try is_int.

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

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接