Заменить несколько вхождений одного символа с помощью preg_replace?

Скажем, у меня есть строка вроде этого:

$string = "hello---world";

Как мне пойти на замену --- с помощью одного дефиса? Строка может выглядеть так:

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

Желаемый результат должен быть:

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

Ответ 1

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

Ответ 2

Чтобы удалить их с начала и конца:

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

Ответ 3

попробуйте $string = preg_replace('/-+/', '-', $string)

Ответ 4

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

Ответ 5

Здесь функция, которую я использую - работает как шарм:)

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