views:

45

answers:

4

Hi all,

A newbie question:

Let's say I have a string like this:

$string = "hello---world";

How would I go about replacing the --- with a single hyphen? The string could easily look like this instead:

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

The desired result should be:

$string = "hello-world-what-up";
+3  A: 
$string = preg_replace('/-{2,}/','-',$string);
Mark Baker
+1 for braces usage.
Jason McCreary
Is the braces performance significantly better then just '-+'?
Wrikken
Thanks Mark! :-DIs it just as easy to have it remove a hyphen, if the string starts with one?For instance having "--hello---world" turning out to be "hello-world"?
KasperFP
@KasperFP: That would be `preg_replace('/^-+/','',$string)`
Felix Kling
For completeness, remove them at the end as well.`preg_replace('/^-+|-+$/','',$string)`
pritaeas
Thanks Felix, pritaeas
Mark Baker
A: 

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

Raja
A: 
$string = preg_replace('/--+/', '-', $string);
pritaeas
A: 

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;
}