Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 must be an alphabetical character [a-zA-Z].

like image 563
Nahydrin Avatar asked Dec 22 '25 23:12

Nahydrin


2 Answers

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.

like image 126
stema Avatar answered Dec 24 '25 11:12

stema


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 )
like image 24
Daniel Haley Avatar answered Dec 24 '25 12:12

Daniel Haley