【问题标题】:Regex: extract first and last child directories from URL正则表达式:从 URL 中提取第一个和最后一个子目录
【发布时间】:2011-12-04 09:38:12
【问题描述】:

我需要一个匹配两个虚拟文件夹的正则表达式;给定 URL 中的第一个和最后一个:

www.example.com/first_folder/some/additional/bunch/of/folders/last_folder/

到目前为止,我有这个正则表达式:(?<!/)/[^/?#]+,但它匹配所有文件夹:(

我需要这个来在 WordPress 中使用重写规则。将http://mysite/project/1 重写为http://mysite/index.php?pagename=project&id=1 的快速而肮脏的示例:

$newrules = array();
$newrules['(project)/(\d*)$'] = 'index.php?pagename=$matches[1]&id=$matches[2]';

【问题讨论】:

    标签: regex wordpress url-rewriting


    【解决方案1】:

    快速而肮脏的解决方案,即没有对十亿个可能的 url 组合等进行彻底测试,所以请谨慎对待..

    .*?/(\w+)/.*?/(\w+)/$
    

    输入:

    www.example.com/first_folder/some/additional/bunch/of/folders/last_folder/

    输出:

    $1 prints first_folder
    $2 prints last_folder
    

    【讨论】:

    • @numediaweb 没有问题。请小心,因为正则表达式是脆弱的野兽:)
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多