0

I want to remove all characters with ascii codes 32 - 47 and some more from string. Exactly !"#$%&'()*+,-./\~.

I tried:

$string = preg_replace('/\s\!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\\~/', '', $string);

But it returned false. What am I doing wrong? Thanks.

Legionar
  • 7,472
  • 2
  • 41
  • 70
  • 1
    You should really read about [**character classes**](https://www.regular-expressions.info/charclass.html). See https://stackoverflow.com/questions/1545751/how-to-back-reference-inner-selections-in-a-regular-expression/1553171#1553171, https://stackoverflow.com/questions/9801630/what-is-the-difference-between-square-brackets-and-parentheses-in-a-regex – Wiktor Stribiżew Oct 26 '17 at 21:12
  • I read this http://www.regular-expressions.info/unicode.html. So I was close to find it :) – Legionar Oct 26 '17 at 21:12

1 Answers1

1

To use the characters just include them in a character class:

$string = preg_replace(':[\s!"#$%&\'()*+,-./\\\~]:', '', $string);

Or use ASCII hexadecimal for the range and characters:

[\x20-\x2f\x5c\x7e]

Or use the actual characters in a range as long as you start with the first (space) and end with the last / in the range and then add the rest:

[ -/\\\~]
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87