49

I'd like to use any php function or whatever so that i can remove any HTML code and special characters and gives me only alpha-numeric output

$des = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>";

I want the output become Hello world it s me and love you (just Aa-Zz-0-9-WhiteSpace)

I've tried strip_tags but it removes only HTML codes

$clear = strip_tags($des); 
echo $clear;

So is there any way to do it?

9 Answers 9

149

Probably better here for a regex replace

// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &amp;
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);

Or, in one go

$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));
9
  • thanks a lot , it is very helpful and works perfect also thanks for explaining it step by step. Commented Aug 20, 2011 at 1:13
  • chuckles I'd +1'd yours as soon as I saw it :D
    – Mez
    Commented Aug 20, 2011 at 1:33
  • 1
    Fatal error: Call to undefined function html_entities_decode()
    – enloz
    Commented Apr 5, 2012 at 3:30
  • 1
    doesn't that code replace alphanumerics with spaces, rather than non-alphanumerics? that is: shan't the /[A-Za-z0-9]/ be inverted?
    – umläute
    Commented Feb 18, 2013 at 13:58
  • 1
    Any thoughts on escaping ' and " in the regex?
    – mike
    Commented Jul 1, 2013 at 12:06
13

Strip out tags, leave only alphanumeric characters and space:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

Edit: all credit to DaveRandom for the perfect solution...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));
1
  • 5
    +1 for Matt, but you should probably make strip_tags($des) into strip_tags(html_entity_decode($des)) or you are at risk of ending up with some stray amp, lt, gt etc in the output...
    – DaveRandom
    Commented Aug 20, 2011 at 1:14
6

All the other solutions are creepy because they are from someone that arrogantly simply thinks that English is the only language in the world :)

All those solutions strip also diacritics like ç or à.

The perfect solution, as stated in PHP documentation, is simply:

$clear = strip_tags($des);
1
  • Yea, as a english speaker can understand what you are saying. Your solution is perfect for my issue. Was trying to use too many rules and diacritics were getting stripped. Thanks!
    – Woody
    Commented Jul 17, 2021 at 6:06
1

In a more detailed manner from Above example, Considering below is your string:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';

Code:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows: English letters (Capital and small), 0 to 9 and characters !@#$%^&*().

Removes: All html tags, and special characters other than above

2
  • thank you so much for your answer, I liked this idea so much. Commented Dec 24, 2013 at 16:31
  • @JackBen: glad to see your response :) Commented Dec 26, 2013 at 6:58
1

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));
1

Here's a function I've been using that I've put together from various threads around the net that removes everything, all tags and leaves you with a perfect phrase. Does anyone know how to modify this script to allow periods (.) ? In other words, leave everything 'as is' but leave the periods alone or other punctuation like and ! or a comma? let me know.

function stripAlpha( $item )

{

    $search     = array( 
         '@<script[^>]*?>.*?</script>@si'   // Strip out javascript 
        ,'@<style[^>]*?>.*?</style>@siU'    // Strip style tags properly 
        ,'@<[\/\!]*?[^<>]*?>@si'            // Strip out HTML tags
        ,'@<![\s\S]*?–[ \t\n\r]*>@'         // Strip multi-line comments including CDATA
        ,'/\s{2,}/'
        ,'/(\s){2,}/'

    );

    $pattern    = array(

         '#[^a-zA-Z ]#'                     // Non alpha characters
        ,'/\s+/'                            // More than one whitespace

    );

    $replace    = array(
         ''
        ,' '

    );

    $item = preg_replace( $search, '', html_entity_decode( $item ) );
    $item = trim( preg_replace( $pattern, $replace, strip_tags( $item ) ) );
    return $item;

}
1
  • How to have UTF-8 characters acceptable,but remove other special caharacters
    – aΨVaN
    Commented Jun 8, 2015 at 5:48
0

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

0

preg_replace('/[^a-zA-Z0-9\s]/', '',$string) this is using for removing special character only rather than space between the strings.

0

Remove all special character don't give space write in single line

trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', 
urldecode(html_entity_decode(strip_tags($string))))));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.