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