Force/Limit the post/page slug to accept only url friendly characters

For now I used the sanitize_title filter, and removed all unwanted characters, which forces my users to use only [a-z0-9-] as a valid input for titles.

## Allow only [a-z0-9-] in the slug
function my_clear_title($title) {

    $pattern = '/[^a-z_0-9- ]/i';
    $replace_with="";
    return preg_replace($pattern, $replace_with, $title);
}
add_filter('sanitize_title', 'my_clear_title', 3, 1);
  • I had to use a higher priority (3) to make sure my filter will run before wordpress builtin filters.