← W4DEV JOURNAL

Strip out all Html, Php, Js tags by wp_strip_all_tags WordPress Function

wp_strip_all_tags is a built in WordPress function used to strip tags out of a given string. It is a modified, extended version of the PHP strip_tags function. strip_tags removes HTML and PHP tags from a string, and wp_strip_all_tags does two more things on top of that: it also removes the content of JavaScript and inline style tags, and it can optionally convert line breaks into white space.

The wp_strip_all_tags function is located in the /wp-includes/formatting.php file. Here is a simplified version of its definition –

function wp_strip_all_tags( $text, $remove_breaks = false ) {
    $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text );
    $text = strip_tags( $text );

    if ( $remove_breaks ) {
        $text = preg_replace( '/[\r\n\t ]+/', ' ', $text );
    }

    return trim( $text );
}

You can use this function in your php file for stripping HTML, PHP, JS, CSS tags.
Example:

$raw_text = '<div>Test paragraph.</div><script type="text/javascript">...</script><style type="text/css"></style><!-- Comment -->';
$striped_text = wp_strip_all_tags($raw_text, true);

// will return - "Test paragraph."

Arguments Reference:
– First parameter is the (string) you want to strip tags from.
– Second parameter is a (boolean), if set to true, line breaks will also be removed. The default is false, which keeps line breaks in place.

Filed under

KEEP EXPLORING

More practical tools for WordPress.

Browse the complete journal or find a focused plugin for your next project.