Skip to content

Instantly share code, notes, and snippets.

@anovsiradj
Last active August 28, 2015 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anovsiradj/443ce0592ac6ff2330fd to your computer and use it in GitHub Desktop.
Save anovsiradj/443ce0592ac6ff2330fd to your computer and use it in GitHub Desktop.
Regex validate username with PHP.
<?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