2010-07-22 54 views
13

比方說,我有一個這樣的字符串:使用preg_replace替換多次出現的相同符號?

$string = "hello---world"; 

我將如何去用一個連字符替換---? 字符串可以很容易地像這個:

$string = "hello--world----what-up"; 

期望的結果應該是:

$string = "hello-world-what-up"; 

回答

28
$string = preg_replace('/-{2,}/','-',$string); 
+0

+1括號使用。 – 2010-07-22 13:18:57

+1

大括號的表現明顯好於「 - +」嗎? – Wrikken 2010-07-22 13:28:58

+0

謝謝馬克! :-D 如果字符串以一個字符串開頭,刪除連字符就簡單嗎? 例如「--hello --- world」變成了「hello-world」? – kasperwf 2010-07-22 13:30:42

0

嘗試$string = preg_replace('/-+/', '-', $string)

0
$string = preg_replace('/--+/', '-', $string); 
0

下面是我使用的功能 - 作品像一個魅力:)

public static function setString($phrase, $length = null) { 
    $result = strtolower($phrase); 
    $result = trim(preg_replace("/[^0-9a-zA-Z-]/", "-", $result)); 
    $result = preg_replace("/--+/", "-", $result); 
    $result = !empty($length) ? substr($result, 0, $length) : $result; 
    // remove hyphen from the beginning (if exists) 
    $first_char = substr($result, 0, 1); 
    $result = $first_char == "-" ? substr($result, 1) : $result; 
    // remove hyphen from the end (if exists) 
    $last_char = substr($result, -1); 
    $result = $last_char == "-" ? substr($result, 0, -1) : $result;  
    return $result; 
} 
2

要從開頭和結尾刪除:

$string = trim($string, '-'); 
+1

問問題3年後發佈部分答案並不真實有用 – 2013-07-21 18:49:27

+2

很多人來通過Google **每日**。這些信息每三天讀取一次,並持續三年。不幸的是,無法添加此評論。 – dragonattack 2013-08-05 02:11:02

相關問題