skip to Main Content

I have a php input filter that cleans all unwanted characters from a string.
This:

$clean = preg_replace("/[^a-z0-9 .-"_',]/i", "", $string);

This works fine, but I also what to preserve all character returns in the string.
I’ve tried different things like adding ‘nr’ or ‘R’ or ‘nr’ to the list of characters in the brackets or adding ‘/m’ to the flag.
I’m just not finding the right combo.
Any suggestions?

2

Answers


  1. You can use a character class to match any non-printable characters:

    $clean = preg_replace("/[^a-z0-9 .-"_',p{C}]/i", "", $string);
    
    Login or Signup to reply.
  2. You can use

    $clean = preg_replace("/[^a-z0-9 ."_',rn-]/i", "", $string);
    

    Note

    • The added rn
    • The dot does not have to be escaped inside a character class
    • The - char is put to the end of the character class and it does not have to be escaped there.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search