2010-07-22 50 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

相关问题