I have this pattern:
preg_match("/[a-zA-Z0-9~!@#$%&_-.!\?\,\' ]$/", $value_of_field)

when $value_of_field contains carriage returns then the match doesn't work. But when it's a single line it works fine. $value_of_field contains the value of a textarea form field.

What am I missing here?

    A carriage-return or newline is a character. If you want to allow them, then you need to add them to your character class as '\r' and '\n' respectively. If you want to allow any white-space (space, newline, carriage-return, or tab), you can use '\s' to represent any white-space character.

      NogDog - I forgot to mention that I did try the options \r \n and \s. I assumed that since they didn't work then they were not the solution. So maybe I'm doing something else wrong. I'll keep testing and post back if I figure it out.

      Thanks.

        Sorry for wasting your time. I had duplicated the piece of code by mistake that had the regex in it. After duplicating it I updated one of them but not the other which made it appear that the regex was not matching the subject. By the way NogDog was exactly right in his response.

          Your pattern of /[a-zA-Z0-9~!@#$%&_-.!\?\,\' ]$/ could be simplified:

          /^[a-z0-9~!@#$%^&*_.!?,'\s-]*$/i
          

          Using the 'i' modifier makes things case insensitive (which eliminates the need to list both upper and lowercase characters). Since you are using double quotes for your pattern (personally, I prefer single quotes), the single quote within the class in this case doesn't need escaping (nor does characters like . ! ? ,) as most meta characters lose their special meaning inside a class. Some characters might retain this status depending on their location within the class, such as the dash. This character doesn't need escaping on the condition that it is the very first or very last character listed within the character class.

          If enforcing the character class shorthand \w to be strictly equal to a-zA-Z0-9_, we can use setlocale() and shorten the pattern even more:

          setlocale(LC_CTYPE, 'C');
          preg_match("/^[\w~!@#$%^&*.!?,'\s-]*$/", $value_of_field);
          

          Performance gains / hindrances is probably debatable (as is regex pattern readability). There's nothing wrong with (unecessarily) escaping certain characters or listing a range of characters instead of using shorthand character classes (like \s or \w). Just adds clutter to the pattern imo (but this is all subjective I'd wager). To each his/her own?

            Write a Reply...