Last active
August 28, 2015 09:40
-
-
Save anovsiradj/443ce0592ac6ff2330fd to your computer and use it in GitHub Desktop.
Regex validate username with PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @version 20150828 | |
*/ | |
function username($str) { | |
$bool = preg_match('/^[a-zA-Z][a-zA-Z0-9_]+$/', $str); | |
$status = ($bool ? "<b>Good</b>" : "Bad"); | |
echo $status." : ".$str."\n"; | |
} | |
$kind = array( | |
"2anov", | |
"22anov", | |
"an-ov", | |
"_anov", | |
"an_ov", | |
"_1anov", | |
"an_ov22", | |
"a_5_nov22", | |
"a__nov22" | |
); | |
echo "<pre style='font-size:40px;'>"; | |
for ($i=0; $i < count($kind); $i++) { | |
username($kind[$i]); | |
} | |
// result | |
/* | |
Bad : 2anov | |
Bad : 22anov | |
Bad : an-ov | |
Bad : _anov | |
Good : an_ov | |
Bad : _1anov | |
Good : an_ov22 | |
Good : a_5_nov22 | |
Good : a__nov22 | |
*/ | |
/* | |
Hal yang saya pelajari: | |
- [..] yang pertama hanya memindai karakter pertama dari string. | |
- [..] yang kedua akan memindai semua string setelah string pertama. | |
- +$ perintah, string harus sama dengan karakter dalam [..]. | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment