hom*_*rrr 4 php apache .htaccess mod-rewrite
我想在URL中应用页面HTML标题
例如在这里(stackoverflow)url是这样的:
http://stackoverflow.com/questions/10000000/get-the-title-of-a-page-url
Run Code Online (Sandbox Code Playgroud)
你可以看到"get-the-title-of-page-url"部分,它是页面标题
我的意思是当用户去spowpost.php?post = 1
当页面加载时显示的实际网址是spowpost.php?post = 1 $ title = .. the_title ..
我怎样才能做到这一点?
编辑:我正在考虑htaccess,但我不太了解这个教程将有助于这个例子.
你可以使用.htaccess.例如:
RewriteEngine On
RewriteRule ^questions/(\d+)/([a-z-]+) index.php?id=$1&title=$2 [L]
Run Code Online (Sandbox Code Playgroud)
您的PHP页面(index.php)在以下位置接收id和title作为参数$_GET[]:
echo $_GET['title'];
// get-the-title-of-a-page-url
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用它(或更容易的id)从数据源中检索正确的项目:
// Assuming you didn't store the - in the database, replace them with spaces
$real_title = str_replace("-", " ", $_GET['title']);
$real_title = mysql_real_escape_string($real_title);
// Query it with something like
SELECT * FROM tbl WHERE LOWER(title) = '$real_title';
Run Code Online (Sandbox Code Playgroud)
假设您在某种URL中确实有一个id参数,则更容易根据该值进行查询.标题部分实际上只能用于制作可读的URL,而无需在PHP中对其进行操作.
相反,要将标题转换为format-like-this-to-use-in-urls,请执行:
$url_title = strtolower(str_replace(' ', '-', $original_title));
Run Code Online (Sandbox Code Playgroud)
以上假设您的标题不包含任何在URL中非法的字符...
$article_link = "http://example.com/spowpost.php?post=$postid&$title=$url_title";
Run Code Online (Sandbox Code Playgroud)
或者输入.htaccess:
$article_link = "http://example.com/spowpost$postid/$url_title";
Run Code Online (Sandbox Code Playgroud)