donglengli0644 2010-02-06 20:29
浏览 41
已采纳

PHP和Apache - 解析mod_rewrite网址

I have my server's apache configured to redirect every request into index.php, so that I can use urls like :

http://www.website.com/about/us

Now I need to parse the url in order to determine if each route exists and what to expect from it, so I can set a database table to save the routes and so my clients can edit their routes as they like them to be. Thing is, I'm not able to do the parsing so far.

Here's my code :

$uri = 'about/us';
$regex = '(page(/<action>))';
if ( ! preg_match($regex, $uri, $matches)) {
    echo 'the route doesn\'t match';
    exit();
}

It always shows up that echo message. What am I doing wrong?

edit :

The reason why I need regex is as follows. Imagine I have a url segment like :

/user/yoda

The regex here would be usefull to parse the first argument as an action or page, and the second as a key that will only allow a certain set of chars, like if I want to expect, in this case, the second paramenter only to match "_-azAZ09", something like this. In other words, the set of regex expressions would me compared to the uri in order to determine if any of them matches the uri, and determine the action to take from that on. Using the explode function would make me evaluate the uri segments later in the code, wich I'd like to avoid. If there's no match to the uri, immediatelly forward the page to a 404 one and break the operation. Don't know if I made myself clear ..

  • 写回答

3条回答 默认 最新

  • dsztc99732 2010-02-06 20:37
    关注

    Instead of using regular expressions, why not simply split the incoming URI?

    $uri = 'about/us';
    list($page, $action) = explode('/', $uri);
    

    If you need more than two, simply remove the list:

    $pagePath = explode('/', $uri);
    

    But, if you insist on using regular expressions, this will do:

    $regex = '#(?P<page>.*)/(?P<action>.*)#';
    

    However, it offers you nothing special except that $matches will now contain $matches['page'] and $matches['action'] - but if you really need it, youcan use list() as shown above.


    Using the explode function would make me evaluate the uri segments later in the code, wich I'd like to avoid

    Instead of making sure the page is valid by it's character set, why not compile a list of valid pages lookup table and just use php's in_array which is much faster than a regular expression? Extracting the URL segments into an array will allow you to have multi-dimension arrays validated in no time.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题