如何使用post title slug重写url?

时间:2011-06-21 06:26:52

标签: php .htaccess url-rewriting

考虑一个网址

www.example.com/paper-ads-details.php?req=43397&rnd=1308546000

我想将此网址更改为:

www.example.com/jobs-in-chanai.php

其中req=43397指向标题为作业的帖子 我怎么能改写那个?请帮帮我。

3 个答案:

答案 0 :(得分:1)

  1. 如果要使用.htaccess,则需要编写脚本以静态生成重写规则,因此.htaccess文件包含如下行 RewriteRule ^jobs-in-chanai.php /paper-ads-details.php?req=43397&rnds=1308546000 [L]

  2. 在PHP中处理请求开头的路由。解析(并过滤)网址以根据slug而不是req和rnds参数查找帖子。如果需要,请缓存结果。

答案 1 :(得分:1)

在您的数据库中,您需要一个“clean url”或“slug”列以及提到的.htaccess规则。

我使用此功能(不是我的代码):

   function makeSlug($string, $force_lowercase = true, $anal = false) {
     $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;

}

我将其保存在专栏中并执行以下操作:

"SELECT * FROM `content` WHERE `clean_url` = '" . mysql_real_escape_string($cleanURL) . "'";

答案 2 :(得分:1)

经过艰难时期,我顺道完成了,现在为其他用户分享... 假设所需的网址为www.example.com/programmer-Jobs-in-luton
规则将类似于...
RewriteRule ^([a-zA-Z0-9-]+)$ job-details.php?slug=$1 [L]