Q:

Stripping input to complete plain text

Currently finalising the coding for my comment system, and it want it to work a little how Stack Overflow works with their posts etc, I would like my users to be able to use BOLD, Italic and Underscore only, and to do that I would use following:

_ Text _   * BOLD *  -Italic-

Now, firstly I would like to know a way of stripping a comment completely clean of any tags, html entities and such, so for example, if a user was to use any html / php tags, they would be removed from the input. 
I am currently using Strip_tags, but that can leave the output looking quite nasty, even if an abusive or blatent XSS/Injection attempt has been made, I would still like the plain-text to be outputted in full, and not chopped up as strip_tags seems to make an absolute mess when it comes to that.
What I will then do, is replace the asterisks with bold html tags, and so on AFTER stripping the content clean of html tags.
How do people suggest I do this, currently this is the comment sanitize function
function cleanNonSQL( $str )
{
    return strip_tags( stripslashes( trim( $str ) ) );
}

A:

PHP tags are surrounded by <? and ?>, or maybe <% and %>on some ages-old installations, so removing PHP tags can be managed by a regex:
$cleaned=preg_replace('/\<\?.*?\?\>/', '', $dirty);
$cleaned=preg_replace('/\<\%.*?\%\>/', '', $cleaned);

Next you take care of the HTML tags: These are surrounded by < and >. Again you can do this with a regex
$cleaned=preg_replace('/\<.*?\>/','',$cleaned);

This will transform 
$dirty="blah blah blah <?php echo $this; ?> foo foo foo <some> html <tag> and <another /> bar bar";

into 
$cleaned="blah blah blah  foo foo foo  html  and  bar bar";

