Escape user input before preg_match or preg_replace

By pimteam on May 14, 2014

Sometimes you need to do preg_replace on user input. Don't forget to escape all special characters or you'll get funny results. Here is how:

$input = str_replace(array('^', '.', '|', '(', ')', '[', ']', '*', '+', '?', '{', '}', '$' ), 
        array('\^', '\.', '\|', '\(', '\)', '\[', '\]', '\*', '\+', '\?', '\{', '\}', '\$' ), $input);

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.