Заменить несколько вхождений одного и того же символа, используя preg_replace?

13
задан Cœur 30 April 2017 в 22:48
поделиться

4 ответа

$string = preg_replace('/-{2,}/','-',$string);
29
ответ дан 1 December 2019 в 20:10
поделиться

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

0
ответ дан 1 December 2019 в 20:10
поделиться
$string = preg_replace('/--+/', '-', $string);
0
ответ дан 1 December 2019 в 20:10
поделиться

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

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
ответ дан 1 December 2019 в 20:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: