How to sanitize the post_name value before inserting in WordPress?
Some solution might be found at http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/
Also, you might want to do it as follows:
$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
$post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name)));
Simple:
$post_title = sanitize_title_with_dashes($post_title);
But WordPress does this for you already. I assume you need it for something different?
I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp_post_insert() in your insertion script.
$new_post_id = wp_insert_post(array( 'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;" ));
At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable.
This function can be used by simply doing include( "wp-config.php" );
and going about your business without any other PHP overhead.
If you are dealing with some funky titles to begin with, a simple strip_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)