如何用短划线替换空格时在网址中处理短划线

时间:2017-10-17 07:33:39

标签: php .htaccess url mod-rewrite

我目前将我的htaccess设置为:

RewriteRule ^post/([0-9]+)/([a-zA-Z0-9_-]+) post.php?id=$1

这会将我的链接显示为

post/476/title-of-the-page

但是如果我的标题中有 - ,则显示三个

Title - Of The Page

变为

post/476/title---of-the-page

这是我目前处理链接的功能,但我不确定如何正确处理

function slug($string, $spaceRepl = "-") {
    // Replace "&" char with "and"
    $string = str_replace("&", "and", $string);
    // Delete any chars but letters, numbers, spaces and _, -
    $string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
    // Optional: Make the string lowercase
    $string = strtolower($string);
    // Optional: Delete double spaces
    $string = preg_replace("/[ ]+/", " ", $string);
    // Replace spaces with replacement
    $string = str_replace(" ", $spaceRepl, $string);
    return $string;
}

我可以更改preg_replace以删除-,但有些帖子会将其用于不同用途。

2 个答案:

答案 0 :(得分:1)

我为干净的slu that做了这个功能。它将所有多个短划线替换为单个短划线删除所有特殊字符。也许对你有帮助。

function clean($string) {
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

    return strtolower(preg_replace('/-+/', '-', $string)); // Replaces multiple hyphens with single one.
}

echo clean("Title - Of The Page");

Demo

注意:也许它不是那么理想,所以这个答案是开放的建议

答案 1 :(得分:1)

您可以像这样替换多个分隔符:

$string = preg_replace("/-+/", "", $string);

在您的函数上下文中:

<?php

echo slug("Foo - Bar"); // foo-bar
function slug($string, $spaceRepl = "-") {
    // Replace "&" char with "and"
    $string = str_replace("&", "and", $string);
    // Delete any chars but letters, numbers, spaces and _, -
    $string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
    //delete multiple separator
    $string = preg_replace("/".$spaceRepl."+/", "", $string);
    // Optional: Make the string lowercase
    $string = strtolower($string);
    // Optional: Delete double spaces
    $string = preg_replace("/[ ]+/", " ", $string);
    // Replace spaces with replacement
    $string = str_replace(" ", $spaceRepl, $string);
    return $string;
}

修改

或者您可以像这样更改str_replace

<?php

echo slug("Foo -    Bar"); // foo-bar
function slug($string, $spaceRepl = "-") {
    // Replace "&" char with "and"
    $string = str_replace("&", "and", $string);
    // Delete any chars but letters, numbers, spaces and _, -
    $string = preg_replace("/[^a-zA-Z0-9 _-]/", "", $string);
    // Optional: Make the string lowercase
    $string = strtolower($string);
    // Optional: Delete double spaces
    $string = preg_replace("/[ ]+/", " ", $string);
    // Replace spaces with replacement
    $string = preg_replace("/\s+/", "-", $string); // new way
    //$string = str_replace(" ", $spaceRepl, $string); // old way
    return $string;
}