Afonso
Afonso

Reputation: 21

php regex for min and max number length

if(strlen(trim($steamid)) != 0)
            {
                $regex = "/^STEAM_0:(0|1):[0-9]{1}[0-9]{0,8}$/";
                if(!ereg($regex, $ssteamid)){
                    echo "STEAM ID invalida";
                }
            }

My problem is that this isn't working as it should.

STEAM ID's have maximum of 18 characters and minimum of 17.

they always start with: STEAM_0:

Two true examples would be: STEAM_0:0:11111111 ; STEAM_0:1:1111111

And another thing is that after STEAM_0: always come an 0 or an 1 like demonstrated in the examples.

Upvotes: 2

Views: 3298

Answers (4)

Spudley
Spudley

Reputation: 168655

You should be avoiding use of ereg() and its related functions; they've deprecated for quite a long time in PHP. Use thepreg_xx() functions instead (preg_match() in this case).

One of the differences between preg_match() and ereg() is that ereg() does not expect you to include the slash characters to start and end the regex, whereas preg_match() does. This is probably the main reason your code isn't working: since you've included the slashes, your use of ereg() won't work, but is you switch to preg_match(), the same expression should work fine.

So a simple change to preg_match() should sort you problem. But while I'm here, I may also suggest that you can shorten your regex string quite considerably. Try something like this:

$regex = "/^STEAM_0:[01]:[0-9]{8,9}$/";
if(!preg_match($regex, $ssteamid)) {
    echo "STEAM ID invalid";
}

Hope that helps.

Upvotes: 0

miku
miku

Reputation: 188014

This:

$regex = "/^STEAM_0:(0|1):[0-9]{1}[0-9]{0,8}$/";

could be writter shorter as:

$regex = "/^STEAM_0:[01]:[0-9]{1,9}$/";

Since your ID is 17 or 18 chars long, adjust the regex to it:

$regex = "/^STEAM_0:[01]:[0-9]{7,8}$/";

Finally, note that ereg is deprecated as of PHP 5.3. This snippet shows your php/regex with preg_match:

<?php

$steamid = "STEAM_0:0:11111111";

if(strlen(trim($steamid)) != 0)
{
    $regex = "/^STEAM_0:[01]:[0-9]{7,8}$/";
    if(!preg_match($regex, $steamid))
    {
        echo "STEAM ID invalida.\n";
    } else {
        echo "STEAM ID valida.\n";
    }
}
?>

Upvotes: 3

codaddict
codaddict

Reputation: 454960

Try this:

$regex = "/^STEAM_0:(0|1):[0-9]{8,9}$/";

It matches:

  • STEAM_0: at the beginning, followed by
  • a 0 or a 1, followed by a :, followed by
  • Either 8 or 9 digits, making the total number of characters 17 or 18

Upvotes: 0

ArtBIT
ArtBIT

Reputation: 3989

If the minimum length is 17 and the max length is 18, then you guys are looking at this at the wrong way. This should do the job for you:

$regex = "/^STEAM_0:(0|1):[0-9]{7}[0-9]?$/";

And also, when in doubt, test your regexp with some of the online regexp tools like http://www.regexplanet.com/simple/index.html

Upvotes: 0

Related Questions