I am trying to validate company names in PHP which should allow, periods, dashes, but not in the first or last part of the name. This is my code
!preg_match("/^[a-zA-Z'. -] $/", stripslashes($post['company_name']))
For now, it allows dashes and perios as first or last character of the company name. I need to DISALLOW periods and dashes as FIRST and LAST characters. How can I achieve this?
CodePudding user response:
Here is my answer where Alphanumeric can be First and Last, and periods and dashes CANNOT be first and Last
!preg_match("/^[a-z0-9](?:[a-z0-9'. -]*[a-z0-9])?$/i", stripslashes($post['signup_name']))
Thanks for the guys who replied!
CodePudding user response:
You just need to force a match to alphabetic characters at the beginning and end of the string:
preg_match("/^[a-z](?:[a-z'. -]*[a-z])?$/i", stripslashes($post['company_name']))
Note:
- if you use the
i
(case-insensitive) flag to the regex you don't need to specifyA-Z
as well asa-z
. - I've assumed you don't want the name to start or end with a single quote either. If you do, change the regex to
^[a-z'](?:[a-z'. -]*[a-z'])?$
Finally you might want to include digits (\d
or 0-9
) in the regex's character classes as there are many company names (e.g. "F5") that contain them.