使用strtolower()和preg_replace()创建slug

时间:2012-10-26 11:57:30

标签: php regex clean-urls

  

可能重复:
  Regular Expression Sanitize (PHP)

我想让我的链接SEO。在我开始之前,链接看起来像这样:

http://www.domain.tld/index.php?page=blog

我的目标是将其更改为:http://www.domain.tld/blog。现在有效。

我将htaccess更改为:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)$
RewriteRule ^index\.php$ /%1? [R=301,L]
RewriteRule ^blog/(\d+)-([\w-]+)$ index.php?page=single_news&id=$1&headline=$2

现在我想更改任何博客条目标题的URI。它们看起来像这样:http://www.domain.tld/index.php?page=single_news&id=2&headline=This%20Is%20A%20Headline

我想让它们看起来像这样:http://www.domain.tld/blog/2-this-is-a-headline 我在div-class“news_headline”中生成我的标题链接(见下文)。

<div id="main">
<?php
$query = "SELECT `id`, `headline`, `writer`, `content`, DATE_FORMAT(date,\"%d. %M %Y\") AS `date` FROM `blog` ORDER BY `id` DESC";
$news_resource = mysql_query($query) or die(mysql_error());
?>

<?php
$all_news = array();
$five_news = array();
for($i = 0; $news = mysql_fetch_object($news_resource); $i++){
if($i < 5){
  $five_news[] = $news;
}
$all_news[] = $news;
}
?>

<?php foreach($five_news as $news)
{ ?>

<div class="news_bg">
<div class="news_headline"><a href="blog/<?php echo $news->id; ?>-<?php echo $news->headline; ?>"><?php echo $news->headline; ?></a></div>
<div class="news_infoline_top"><?php echo $news->date; ?> &middot; <?php echo $news->writer; ?></div>
<div class="news_text"><?php echo $news->content; ?></div>
</div>
<?php } ?>
</div>

使用我的htaccess(见上文)链接就像这样:

http://www.domain.tld/blog/2-This Is A Headline

我已经有了这方面的帮助,一个好人给了我这段代码片段,使链接看起来像我想要的,但我不知道如何使用它们:

$urititle = strtolower(preg_replace('/[^\w-]+/','-', $title));

$_GET['headline'] != $urititle

我迷路了。

1 个答案:

答案 0 :(得分:1)

你已经非常接近了:

  • 您将ID放在有趣部分的开头。这允许您通过唯一快速的ID来查询数据库。
  • 您需要了解需要将标题文本转换为 slug 变体,并且您已经知道这是字符串处理。

您还有一些步骤可以完成此操作。索姆注意到:

  • 创建一个执行字符串转换的函数。这里的重要部分是,您可以简单地称之为。
  • 当对文章的请求进入时,根据您从字符串中获取的ID值获取文章:$assigned = sscanf($slug, '%d-', $id);
  • 对于SEO,请执行与创建链接时相同的操作。然后比较当前链接是否正确(标题可能已更改)。如果没有,请永久重定向到正确的链接。

就是这样!