假设我有一个这样的字符串:
$string = "hello---world";
我如何用一个连字符替换---? 字符串很容易看起来像这样:
$string = "hello--world----what-up";
期望的结果应该是:
$string = "hello-world-what-up";
答案 0 :(得分:28)
$string = preg_replace('/-{2,}/','-',$string);
答案 1 :(得分:2)
要从开头和结尾删除它们:
$string = trim($string, '-');
答案 2 :(得分:0)
尝试$string = preg_replace('/-+/', '-', $string)
答案 3 :(得分:0)
$string = preg_replace('/--+/', '-', $string);
答案 4 :(得分: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;
}