【问题标题】:Using regex to do matching in an URL使用正则表达式在 URL 中进行匹配
【发布时间】:2013-03-26 13:55:14
【问题描述】:

我目前正在做一个项目,我需要它来操纵参数以达到美学目的。

add_rewrite_rule( '([^/]*)/user/([^/]+)','index.php?pagename=$matches[1]&username=$matches[2]', 'top' );
-> would correctly retrieve the userID (in this case 232) from the following URL: http://mysite.com/userlisting/user/232

add_rewrite_rule( '([^/]*)/([^/]*)/user/([^/]+)','index.php?pagename=$matches[1]&username=$matches[2]', 'top' );
-> would correctly retrieve the userID (in this case 232) from the following URL: http://mysite.com/parent_directory/userlisting/user/232

现在我可以添加,比如说其中的 10 条规则,以确保完成至少 10 级层次结构,但我想做的是根据当前“用户列表”的多少级别使其具有一定的动态性"有。

任何帮助将不胜感激。

【问题讨论】:

    标签: php regex wordpress url


    【解决方案1】:
     add_rewrite_rule( '([^/]*)/([^/]*)/user/([^/]+)','index.php?pagename=$matches[1]&username=$matches[2]', 'top' );
     -> would correctly retrieve the userID (in this case 232) from the following URL: http://mysite.com/parent_directory/userlisting/user/232
    

    ,不会。

    • $matches[1] 是parent_directory
    • $matches[2] 是userlisting
    • $matches[3] 将是232(即用户ID)

    所以您的内部 URL 将是 index.php?pagename=parent_directory&username=userlisting


    至于实际上,解决问题,取决于您要如何处理多个级别,即如何将它们传递给 php,一种可能性是

    add_rewrite_rule( '(.+?)/user/([^/]+)','index.php?pagename=$matches[1]&username=$matches[2]', 'top' );
    

    在这种情况下会给出

    index.php?pagename=parent_directory/userlisting&username=232

    即,与 url 中存在的一样多的目录将使其进入“页面名称” - 您不会将 / 排除在目录名称的一部分之外。

    但是,如果您希望以不同的方式向 PHP 呈现各种层次结构级别,则可以采用不同的方式。

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多