【问题标题】:Is it possible to target string "--" with regex?是否可以使用正则表达式来定位字符串“--”?
【发布时间】:2016-03-07 10:33:57
【问题描述】:

是否可以在 URL 中的“--”之后定位字符串以重定向到另一个页面?

假设我们有这两个 URL:

1. www.domain.com/some/some2/some3/my-page.html
2. www.domain.com/some/some2/some3/my-page--woohoo.html

第一个只显示 my-page.html 的内容。

我需要将第二个 URL 重定向到

www.domain.com/index.php?pagename=$matches[4]&var=$string

所以在这种情况下应该是:

www.domain.com/index.php?pagename=my-page&var=woohoo

有没有可能?

非常感谢!

【问题讨论】:

  • 一切皆有可能。你试过什么?
  • @Allendar 什么都不是……你不可能是上帝 ;-)
  • 我只有 1000 个看起来像 /some/some2/my-page.html 的 url,需要为许多 em 添加子页面。使用斜杠会很容易,但最后使用 .html 会更复杂,因此双斜杠有望使其工作......

标签: regex apache redirect


【解决方案1】:

是的,这是可能的。我认为您正在寻找这样的东西:

图案:

^(.*?)\/.*\/([a-zA-Z-]+)--(.*)\..*$
  • ^ 断言字符串开头的位置
  • (.*?) 匹配任何字符(换行符除外)作为捕获组
  • \/ 匹配字符 / 字面意思
  • [a-zA-Z-]+ 匹配提到的列表 a-z, A-Z, - 之间的单个字符
  • -- 匹配字符——字面意思
  • $ 断言字符串末尾的位置

替换:

$1/index.php?pagename=$2&var=$3

Online Demo


由于您在问题中使用了apache 标签,这会有所帮助:

#With mod_rewrite
RewriteEngine on
RewriteRule  "(.*?)\/.*\/([a-zA-Z-]+)--(.*)\..*$"  "$1/index.php?pagename=$2&var=$3"  [R,L]

#With RedirectMatch
RedirectMatch "(.*?)\/.*\/([a-zA-Z-]+)--(.*)\..*$" "$1/index.php?pagename=$2&var=$3"

【讨论】:

  • 谢谢你,我会试一试并报告!
  • 它在 htaccess 中工作正常,但是当我尝试通过 PHP 插入它时 (add_rewrite_rule('^(.*?)\/.*\/.*\/([a-zA-Z- ]+)--woohoo\.html$', 'index.php?&pagename=$matches[2]', 'top');),我无法让它工作(调用 www.domain.com/ some/some2/my-page--woohoo.html 返回 http 404)。奇怪的是,当我将规则更改为 add_rewrite_rule('^(.*?)\/.*\/.*\/([a-zA-Z-]+)--woohoo\.html$', 'index. php?&pagename=my-page', 'top');它工作正常。你不知道为什么?
  • 我不确定您到底在寻找什么,但也许 this 帮助
  • 我创建了另一个问题,因为我的实际问题超出了这个问题:stackoverflow.com/questions/35846891/…
【解决方案2】:

您可以在 server.config 或 htaccess 中使用以下规则:

RewriteEngine on


RewriteCond %{THE_REQUEST} /([^/]+)--([^.]+)\.html [NC]
RewriteRule ^ /index.php?pagename=%1&var=%2 [NC,L,R]

这将重定向:

  • /some/some1/some2/my-page--woohoo.html

  • /index.php?pagename=my-page&var=woohoo

【讨论】:

  • 如果页面的名称类似于“my-another-page--woohoo.html” - 它会起作用吗?
  • @Pupik 我编辑了条件模式。它应该适用于多个 - .
  • 不幸的是,这不起作用。即使在 regex101.com 中,它也会显示错误......不知道为什么。不过还是谢谢!
  • @Pupik 不知道为什么它不适合你,我在我的 apache 服务器上测试了两次它对 url 工作正常。
猜你喜欢
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 2012-08-05
相关资源
最近更新 更多