Replace multiple occurrences of same symbol using preg_replace?
Let's say I have a string like this:
$string = "hello---world";
How would I go about replacing the --- with a single hyphen? The stri开发者_如何学Pythonng could easily look like this instead:
$string = "hello--world----what-up";
The desired result should be:
$string = "hello-world-what-up";
$string = preg_replace('/-{2,}/','-',$string);
To remove them from the beginning and the end:
$string = trim($string, '-');
try $string = preg_replace('/-+/', '-', $string)
$string = preg_replace('/--+/', '-', $string);
Here's the function I'm using - works like a charm :)
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;
}
精彩评论