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;
}
Leave A Reply
All content licensed under the Creative Commons License