从漂亮的 url 获取 id 作为 intval
好吧,我已将网址设置为将“news_item.php?id=1”重写为“blog/1/Title-of-post”。
除了当标题开头有数字(例如“blog/23/12-days-to-go”)时它无法找到正确的 ID 时,这非常有效。
这是我的设置方式,也许有人可以理解。
重写规则
RewriteRule ^blog/([0-9]+)/([a-z-]+)/$ ./news_item.php?id=$1&t=$2
RewriteRule blog/([[0-9]+)/([a-z-]+) news_item.php?id=$1&t=$2
从 url 获取 ID
$id = intval($_GET['id']);
然后我只使用
`WHERE `id`=$id`
作为我的查询
链接使用
/blog/$id/$title/
所以它工作正常,除了标题开头有数字时,标题中的数字也可以。谁能建议该怎么做?
Alright, I have my urls set up to rewrite "news_item.php?id=1" to "blog/1/Title-of-post".
This works great apart from when a title has numbers at the start for example "blog/23/12-days-to-go" it can't find the right id.
Here's how I have it setup, maybe someone can make sense of it.
Rewrite rules
RewriteRule ^blog/([0-9]+)/([a-z-]+)/$ ./news_item.php?id=$1&t=$2
RewriteRule blog/([[0-9]+)/([a-z-]+) news_item.php?id=$1&t=$2
Get ID from url
$id = intval($_GET['id']);
Then I just use
`WHERE `id`=$id`
as my query
Link used
/blog/$id/$title/
So it works fine apart from when there is a number at the start of the title, a number within the title is fine though. Can anyone suggest what to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
id 的问题出在你的正则表达式中。你不是在寻找数字。 :
RewriteRule ^blog/([0-9]+)/([A-Za-z0-9-]+)/$ ./news_item.php?id=$1&t=$2
使用类似的内容 标题”之所以有效,是因为您只是将字母字符拉到第一个数字。 (例如“abc123def”变为“abc”)
The problem with the ids is in your regular expression. You aren't looking for numbers. Use something like:
RewriteRule ^blog/([0-9]+)/([A-Za-z0-9-]+)/$ ./news_item.php?id=$1&t=$2
The "number in the title" works because you are only pulling the alpha characters up to the first number. (e.g. "abc123def" becomes "abc")
首先,在您的示例中,您的第二个 RewriteRule 中有一个额外的
[
。如下所示的 RewriteRule 应该按照您希望的方式工作:
以下 URI
/blog/12/24-days-to-go/extra-stuff
应该在 news_item.php 中为您提供以下内容:第三个
/
之后的所有内容。编辑
像 /blog/12/ 这样的 URI 也可以,发送 12 作为
id
并给你一个空的$_GET['t']
First of, in your example you got an extra
[
in your second RewriteRule.A RewriteRule like the following should work as you want it to:
The following URI
/blog/12/24-days-to-go/extra-stuff
should give you the following in news_item.php:Stripping everything after the third
/
.Edit
An URI like /blog/12/ would work as well, sending 12 as the
id
and giving you an empty$_GET['t']