如何在PHP中将URL更改为用户友好的格式

huangapple go评论59阅读模式
英文:

How to change a url to a user friendly one in php

问题

我有一些PHP知识,但完全是自学的,所以我决定开始一个副业项目,因为我喜欢挑战自己。我每天都使用WordPress,所以我想尝试制作自己的小型博客作为学习项目,但不确定如何解决这个URL问题。

我在数据库中有文章,并通过URL检索文章,我希望使用友好的URL。

这是我的URL http://localhost/news/index.php?article_slug=test-example,我想要实现的是 http://localhost/news/test-example

我已经在这里搜索了其他帖子,比如 这个。我的 .htaccess 文件看起来像这样。

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
RewriteRule ^news/(\d+)$ /news/?article_slug=$1 [L]
RewriteCond %{QUERY_STRING} article_slug=(\d+)
RewriteRule ^news$ /news/%1 [R,L]

当我访问所需的URL时,我收到404未找到的错误。

我使用的是XAMPP,不确定这是否与我的问题有关,但我想提一下。

英文:

I have a little php knowledge but am completely self-taught so I decided I want to start a side project as I enjoy challenging myself. I use WordPress daily so I thought I would try to make my own small blog for a learning project but not sure how to approach this URL issue.

I have articles in my database and pulling the article via the url what I am hoping to do is to use a friendly URL.

this is my URL http://localhost/news/index.php?article_slug=test-example
what I'm trying to achieve is http://localhost/news/test-example

I have been searching other posts on here like this one my .htaccess file looks like this.

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
RewriteRule ^news/(\d+)$ /news/?article_slug=$1 [L]
RewriteCond %{QUERY_STRING} article_slug=(\d+)
RewriteRule ^news$ /news/%1 [R,L]

When I go to the desired URL I get a 404 not found.

I'm am using xamp, not sure if this is relevant to my problem, but thought I would mention it.

答案1

得分: 1

你当前的捕获模式 (\d+) 只匹配数字字符串("d" 代表 "digit")。

你可能想要将其更改为类似 (.+) 的模式。或者也许是 ([\w\d-]+) ...

有很好的解释和有价值的工具可用于学习 "正则表达式" 领域。投资于学习它是非常值得的,这些表达式在整个计算机科学中都得到了广泛使用,其背后的技术与特定的编程语言几乎是独立的。

英文:

Your current capturing pattern (\d+) matches only numerical strings ("d" for "digit").

You probably want to change it into something like (.+) instead. Or maybe ([\w\d-]+) ...

There are good explanations and valuable tools available to work into the field of "regular expressions". It is well worth investing into that, such expressions are used throughout computer science and the technology behind that is more or less independent from a specific programming language.

huangapple
  • 本文由 发表于 2023年2月10日 16:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408762.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定