简体   繁体   中英

PHP: Regex match string not preceded by number or space

I've been trying to check if a string value starts with a numerical value or space and act accordingly, but it doesn't seem to be working. Here is my code:

private static function ParseGamertag( $gamertag )
{

    $safetag = preg_replace( "/[^a-zA-Z0-9\s]+/", "", $gamertag ); // Remove all illegal characters : works
    $safetag = preg_replace( "/[\s]+/", "\s", $safetag ); // Replace all 1 or more space characters with only 1 space : works
    $safetag = preg_replace( "/\s/", "%20", $safetag ); // Encode the space characters : works

    if ( preg_match( "/[^\d\s][a-zA-Z0-9\s]*/", $safetag ) ) // Match a string that does not start with numerical value : not working
        return ( $safetag );
    else
        return ( null );

}

So hiphop112 is valid but 112hiphip is not valid. 0down is not valid.

The first character HAS to be an alphabetical character [a-zA-Z] .

Any help is greatly appreciated.

You need to anchor your pattern to the start of the string using an anchor ^

preg_match( "/^[^\d\s][a-zA-Z0-9\s]*/", $safetag )

Otherwise your regex will find a valid match somewhere within the string

You can find a explanation of anchors here on regular-expressions.info

Note the different meaning of the ^ . Outside a character class its an anchor for the start of the string and inside a character class at the first position its the negation of the class.

Try adding the ^ to signify the beginning of the string...

preg_match( "/^[^\d\s][a-zA-Z0-9\s]*/", $safetag )

also, if the first character has to be a letter, this might be better:

preg_match( "/^[a-zA-Z][a-zA-Z0-9\s]*/", $safetag )

Use ^ to mark the beginning of the string (although ^ inside [ ] means not ).

You can also use \w in place of a-zA-Z0-9

/^[^\d\s][\w\s]*/

Add the "begins with carrot" at the beginning of the regex:

/^[^\d\s][a-zA-Z0-9\s]*/

First thing, nothing will match \s as you have replaced all spaces by %20.

Why not just match positively:

[a-zA-Z][a-zA-Z0-9\s]*
preg_match( "/^[a-zA-Z]+[a-zA-Z0-9\s]*/", $safetag ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM