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

Допустим, у меня есть такая строка:

$string = "hello---world";

Как мне заменить --- одним дефисом? Вместо этого строка может легко выглядеть так:

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

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

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

person kasperwf    schedule 22.07.2010    source источник


Ответы (4)


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

$string = trim($string, '-');
person dragonattack    schedule 21.07.2013
comment
Не очень полезно публиковать частичный ответ через 3 года после того, как вопрос задан. - person Gabe Sechan; 21.07.2013
comment
Многие приходят через Google ежедневно. Эта информация читается каждый день в течение этих трех лет, и она будет продолжаться. К сожалению, не удалось добавить это как комментарий. - person dragonattack; 05.08.2013

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

person Raja    schedule 22.07.2010

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

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;
}
person user398341    schedule 17.08.2010

person    schedule
comment
Производительность фигурных скобок значительно лучше, чем просто «-+»? - person Wrikken; 22.07.2010
comment
Спасибо, Марк! :-D Так же легко удалить дефис, если строка начинается с единицы? Например, когда --hello---world оказывается hello-world? - person kasperwf; 22.07.2010
comment
@KasperFP: Это было бы preg_replace('/^-+/','',$string) - person Felix Kling; 22.07.2010
comment
Для полноты картины также удалите их в конце. preg_replace('/^-+|-+$/','',$string) - person pritaeas; 22.07.2010