2017-10-17 196 views
0

目前,我有我的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刪除-秒,但一些帖子將它們用於不同的目的。

+1

1.刪除任何破折號。 2.用一個空格替換連續的空格。 3.用破折號替換空格... – deceze

回答

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; 
} 
+0

第一個選項非常完美!其次沒有,但沒關係。非常感謝@Samy – JayMax

1

我爲乾淨的slu made做了這個功能。它將所有多個破折號替換爲一個破折號來刪除所有特殊字符。也許對你有幫助。

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

注:也許是沒有太大的最優所以這個答案是開放的建議