2010-07-22 15 views

risposta

28
$string = preg_replace('/-{2,}/','-',$string); 
+0

+1 per uso bretelle. –

+1

Le prestazioni delle parentesi graffe sono significativamente migliori rispetto a "- +"? – Wrikken

+0

Grazie Marco! :-D È altrettanto facile rimuovere un trattino, se la stringa inizia con uno? Per esempio avere "--hello --- world" si sta rivelando essere "ciao-mondo"? – kasperwf

0

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

0
$string = preg_replace('/--+/', '-', $string); 
0

Ecco la funzione che sto utilizzando - funziona come un fascino :)

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

Per rimuoverli dal inizio e la fine:

$string = trim($string, '-'); 
+1

Non è molto utile postare una risposta parziale 3 anni dopo che viene posta la domanda –

+2

Molti vengono tramite Google ** al giorno **. Questa informazione viene letta ogni giorno per questi tre anni e durerà. Sfortunatamente, non ho potuto aggiungere questo come commento. – dragonattack

Problemi correlati