-3

I have a PHP Variable which i need to remove all special characters from, like % / é / ! etc

how can i replace all characters OTHER than A-Z / a-z / 0-9 and . (full stop) with a _

charlie
  • 1,356
  • 7
  • 38
  • 76
  • possible duplicate of [Allowing Only Certain Characters In PHP](http://stackoverflow.com/questions/396166/allowing-only-certain-characters-in-php) – Pat J Nov 29 '13 at 16:13

1 Answers1

5

Something like this ought to work.

preg_replace("/[^A-Za-z0-9\.]/", "_", $str);
Lesleh
  • 1,665
  • 15
  • 24
  • Needs `0-9` inside the `[]`. – Pat J Nov 29 '13 at 16:12
  • this doesn't seem to be doing letters like é or anything – charlie Nov 29 '13 at 16:15
  • I believe `[^\w.]` would be an equivalent abbreviation. (`\w` includes `_` too, but replacing `_` with `_` is effectively nothing. If replacing with something other than `_`, then `\w` would not be correct.) – Wiseguy Nov 29 '13 at 16:18
  • I would not assume that `\w` would exclude alphabetic but non-ASCII characters like `é`. Won't that depend on your locale? – Tim Pierce Nov 29 '13 at 16:24
  • @qwrrty PCRE will only match ASCII alphabet unless Unicode is explicitly enabled. Some other regex engines act differently, however, so you make a good point. – Wiseguy Nov 29 '13 at 16:33