2

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].

6 Answers 6

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 )

Comments

2

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]*/

Comments

1

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

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

Comments

1

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]*

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.