PHP: Sanitize a string down to printable characters

I needed a function to make strings into usuable URL identifiers. This function will take an input string and replace all non-url friendly characters with underscores.

function string_sanitize(string $str) {
    // Replace any non-word chars with underscores
    $str = preg_replace("/[\W_]+/", "_", $str);
    // Remove any leading/trailing underscores that are leftover
    $str = trim($str, "_");

    return $str;
}


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.22.27.24
To prevent spam please submit by clicking the kitten: