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].
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With