Search code examples
phpstringformsdrupalsanitization

Exclude characters from check_plain() in Drupal form


I have a text field in my Drupal form, which I need to sanitise before saving into the database. The field is for a custom name, and I expect some users may want to write for example "Andy's" or "John's home".

The problem is, that when I run the field value through the check_plain() function, the apostrophe gets converted into ' - which means Andy's code becomes Andy's code.

Can I somehow exclude the apostrophe from the check_plain() function, or otherwise deal with this problem? I have tried wrapping in the format_string() function, but it's not working:

$nickname = format_string(check_plain($form_state['values']['custom_name'], array(''' => "'")));

Thanks.


Solution

  • No, you can't exclude handling of some character in check_plain(), because it's simply passes your text to php function htmlspecialchars() with ENT_QUOTES flag:

    function check_plain($text) {
      return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
    }
    

    ENT_QUOTES means that htmlspecialchars() will convert both double and single quotes to HTML entities.

    Instead of check_plain() you could use htmlspecialchars() with ENT_COMPAT (so it will leave single-quotes alone):

    htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
    

    but that can cause some security issues.

    Another option is to write custom regular expression to properly sanitize your input.