Заменить несколько вхождений одного и того же символа, используя preg_replace? - PullRequest
13 голосов
/ 22 июля 2010

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

$string = "hello---world";

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

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

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

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

Ответы [ 5 ]

28 голосов
/ 22 июля 2010
$string = preg_replace('/-{2,}/','-',$string);
2 голосов
/ 21 июля 2013

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

$string = trim($string, '-');
0 голосов
/ 17 августа 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;
}
0 голосов
/ 22 июля 2010
$string = preg_replace('/--+/', '-', $string);
0 голосов
/ 22 июля 2010

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

...