please help to validate my username

i know its simple but i can't get it

i want only to validate the first 4 input of the username should be a letter.

i try to use the preg_match function but i can't get it correctly.

This should check the username must start with 4 digit letter followed by numbers or letters.

preg_match('/^[A-Za-z]{4}[A-Za-z0-9]+$/', $username, $matches);

Are you trying to just validate that the first four characters of a username consists of alphabetic characters?

You can use the "substr" function:

$username = "MyUser";
if(preg_match('/[A-Za-z]/', substr('abcdef', 0, 4)) {
    $valid = true;
}
else {
    $valid = false;
}

T_T still not the correct one. anyone help?

$array = array(str_split($string, 4));
if(!is_numeric($array['0']))
{
echo "Te first 4 are letters";
}
else
{
echo "the first 4 are not letters";
}

Haven't tested this yet so please tell if it didn't work.

<?php
$subjects = array(
	'abcd124',
	'abc1234',
	'passesTheTest',
	'fai1TheTest',
        'abc',
        '123',
);

$pattern = '/^[a-zA-Z]{4}/';

foreach( $subjects as $test ){
	if( preg_match( $pattern, $test ) > 0 ){
		echo 'pass'.PHP_EOL;
	} else {
		echo 'fail'.PHP_EOL;
	}
}
pass
fail
pass
fail
fail
fail
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.