I need to verify in php that a string should not start or end with a hyphen (-). The allowed characters are a-z, A-Z, 0-9 and a hyphen anywhere in the middle of the string.
My this regex
/^[a-zA-Z0-9-]+$/
Verifies the occurrence of allowed character expect the condition that the string should not start or end with the hyphen. How do I achieve this? I new to regex.
This should be what you need.
Notice the
Dmodifier. Without it the expression would match a string that ends in a new line. See here: http://blog.5ubliminal.com/posts/surprises-of-php-regexp-the-d-modifier/. Also, I’ve used theimodifier to not have to use[a-zA-Z0-9]. Keeps the expression shorter.Here’s a couple of examples. As the input string ends in a new-line, it should fail, but without the
Dmodifier, even with the$anchor, it passes: