开发者

How to rewrite url with post title slug?

Consider a url

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

I want to change this urls as:

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

where req=43397 is pointing to the p开发者_StackOverflow中文版ost titled as jobs in chanai How may i rewrite that? Please help me.


  1. If you want to use .htaccess, you need to write a script to generate the rewrite rules statically, so the .htaccess file contains lines like
    RewriteRule ^jobs-in-chanai.php /paper-ads-details.php?req=43397&rnds=1308546000 [L]

  2. Handle the routing at the start of the request in PHP. Parse (and filter) the url to look up the post based on the slug rather than the req and rnds parameters. Cache the results if needed.


In your database you need a column for the 'clean url' or 'slug' as well as the .htaccess rules mentioned.

I use this function (not my code):

   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;

}

I save this in a column and do something like :

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


After hard time i got the way, and now sharing it for Other users... Suppose the required Url is www.example.com/programmer-Jobs-in-luton
The Rule will be like...
RewriteRule ^([a-zA-Z0-9-]+)$ job-details.php?slug=$1 [L]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜