Home > other >  Allow Parenthesis and forward slash to this regex
Allow Parenthesis and forward slash to this regex

Time:08-28

I have this regex

!preg_match("/^[a-z0-9](?:[a-z0-9'. -]*[a-z0-9])?$/i", stripslashes($post['job_title']))

and I want to allow numbers parenthesis and also slashes in this regex. because some job title can be "Front-end developer/designer" or "Recruitment Staff (HR)"How can I achieve this?

CodePudding user response:

Okay I managed to make a proper regex for this which allows Slashes within but not at the START/END, and also allows parenthesis within and at START/END.

!preg_match("/^[a-z0-9\(\)](?:[a-z0-9\/\(\)'. -]*[a-z0-9\(\)])?$/i", stripslashes($post['job_title']))

Thanks to @anubhava his reply gave me an idea how to add stuff in the regex

CodePudding user response:

I don't think your intention is being translated to the pattern.

/^[a-z0-9](?:[a-z0-9'. -]*[a-z0-9])?$/i

/^[a-z0-9\(\)](?:[a-z0-9\/\(\)'. -]*[a-z0-9\(\)])?$/i

In the pattern in your question and the oattern in your answer, the third segment (final optional character match) it provides no effective validation. You see the multi-character (zero or more) matching in the middle of the pattern contains all characters in the last character class. In other words, your pattern will behave exactly the same without the last optional check. These are suitable replacements:

/^[a-z0-9](?:[a-z0-9'. -]*$/i

~^[a-z0-9()](?:[a-z0-9/()'. -]*$~i

If you mean to demand that the string ends in alphanumeric or parenthetical character, then remove your ? before the $.

That said, if you want to ensure that:

  • hyphens, spaces, and dots only occur the the middle of the string and
  • all parentheses are properly opened and closed, contain characters between them, and do not occur at the start of the string
  • etc.

then the best strategy will be "test driven development". Create a large, diverse sample of strings as well as unrealistic strings that you know should fail. Then run your current pattern against all strings. Then analyze which cases do not evaluate as expected and adjust your pattern.

  • Related