PHP remove special character from string

169,839

Solution 1

Your dot is matching all characters. Escape it (and the other special characters), like this:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

Solution 2

preg_replace('#[^\w()/.%\-&]#',"",$string);

Solution 3

You want str replace, because performance-wise it's much cheaper and still fits your needs!

$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);

(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)

Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...

Solution 4

Good try! I think you just have to make a few small changes:

  • Escape the square brackets ([ and ]) inside the character class (which are also indicated by [ and ])
  • Escape the escape character (\) itself
  • Plus there's a quirk where - is special: if it's between two characters, it means a range, but if it's at the beginning or the end, it means the literal - character.

You'll want something like this:

preg_replace('/[^a-zA-Z0-9_%\[().\]\\/-]/s', '', $String);

See http://docs.activestate.com/activeperl/5.10/lib/pods/perlrecharclass.html#special_characters_inside_a_bracketed_character_class if you want to read up further on this topic.

Solution 5

<?php
$string = '`~!@#$%^&^&*()_+{}[]|\/;:"< >,.?-<h1>You .</h1><p> text</p>'."'";
$string=strip_tags($string,"");
$string = preg_replace('/[^A-Za-z0-9\s.\s-]/','',$string); 
echo $string = str_replace( array( '-', '.' ), '', $string);
?>
Share:
169,839
user453089
Author by

user453089

Updated on July 25, 2020

Comments

  • user453089
    user453089 almost 4 years

    I have problems with removing special characters. I want to remove all special characters except "( ) / . % - &", because I'm setting that string as a title.

    I edited code from the original (look below):

    preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $String);
    

    But this is not working to remove special characters like: "’s, "“", "â€", among others.

    original code: (this works but it removes these characters: "( ) / . % - &")

    preg_replace('/[^a-zA-Z0-9_ -]/s', '', $String);