开发者

PHP regular expression for alphanumeric and hypen input

Is it possible to validate input depending on whether it only contains a combination of letters, numbers and hyphens (where a hyphen is not repeated twice-in-a-row and does not begins/ends the string)?开发者_如何学编程

Thanks to Validate username as alphanumeric with underscores

I know that the following validates a string based on alphanumeric input with underscores, would it be possible to alter this?

function validate_alphanumeric_underscore($str) 
{
    return preg_match('/^[a-zA-Z0-9_]+$/',$str);
}

Thank you in advance for your help!


This can be done quite easily with a single regular expression:

/^([a-z0-9]+-)*[a-z0-9]+$/i

This meets all your criteria:

  • No double hyphens
  • No beginning/ending hyphens
  • Works when strlen == 1

Matches:

  • a
  • a-a
  • a-a-a

Doesn't match:

  • -
  • a-
  • -a
  • a--a
  • a-a--a

Play with it here.


Assuming a minimum of 2 characters:

This will validate the general format (not starting or ending with a -).

/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i

Then add a simple check for double hyphens using strpos (if it's false, there is no -- in the string, so we want to return true. Otherwise, we want to return false, so that's why the false === is in there):

false === strpos($string, '--');

So, you could do it as:

function validateAlphaNumericUnderscore($string) {
    if (0 < preg_match('/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i', $string)) {
        return false === strpos($string, '--');
    }
    return false;
}

Now, I'm sure there's a way to do it in a single regex (without needing the additional strpos), but I'm blanking on that now. This is a simple regex, and a simple second string comparison (non regex based).

Hopefully this suits your needs...

Edit: In fact, you could make this more efficient by checking for the -- first (since the string function is cheaper than the regex):

function validateAlphaNumericUnderscore($string) {
    if (false === strpos($string, '--')
        return 0 < preg_match('/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i', $string);
    }
    return false;
}


ircmaxell's answer uses a regex and a strpos() check, and is an answer I prefer, but here's how I did it with a single regex. Disclaimer: this has vast room for improvement:

function validate_alphanumeric_hyphenated($str) 
{
    /* 
     * Match either one or more alphanumeric characters, or a sequence with
     * a series of alphanumeric characters without consecutive, leading
     * or trailing hyphens.
     * 
     * Is probably unnecessarily long.
     */
    return preg_match("/^(?:[a-zA-Z0-9]+|[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?!-))*[a-zA-Z0-9])$/", $str);
}


You could do it with two regexes:

if( !preg_match('/(?:^-|-$|-{2,})/',$str) && preg_match(/^[a-zA-Z0-9_]+$/',$str) ) {
     return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜