0

I build a registration page with php. I have to check if username have alphanumeric symbols. So I did it:

$pattern = "[a-zA-Z0-9]{4,10}";

echo "Pattern = $pattern<br>";

echo "Username = $_POST[username]<br>";

echo "res = ";
echo ereg($pattern, $_POST['username']);

The last echo does not print! I try to use "hello" as username. it should be right! What is the problem?

  • 2
    probably because it's deprecated http://php.net/manual/en/function.ereg.php *"Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.* – Funk Forty Niner Apr 27 '15 at 13:11
  • If the function works it would return an array so echoing it wouldn't work. You should be using `preg_match` and you'll need delimiters. – chris85 Apr 27 '15 at 13:13
  • plus, make sure your form element holds the name attribute. Add error reporting to the top of your file(s) right after your opening PHP tag for example ` – Funk Forty Niner Apr 27 '15 at 13:14
  • Maybe the problem is with `echo "Username = $_POST[username]
    ";` without single quotation marks around `username`? Also, echo should print something, `ereg` returns either a match length, or `false`. Try something like `if (ereg ($pattern, $_POST['username'], $regs)) { echo "$regs[0]"; }`
    – Wiktor Stribiżew Apr 27 '15 at 13:16
  • I could maybe be talked in to "*all_the_key*", but definitely not "*all_key_the*". I absolutely disagree with this. It's preposterous and it will not stand... the. – But those new buttons though.. Apr 27 '15 at 13:43

1 Answers1

0

ereg() function is deprecated. Try to use preg_match()

print preg_match('|[a-zA-Z0-9]{4,10}|', 'hello', $matches); 
// true

aslo you should wrap "username" with quotes

echo "Username = $_POST['username']<br>";
Asgu
  • 712
  • 5
  • 15
  • If matches is provided, then it is filled with the results of search. If you want only check match pattern you can remove it. – Asgu Apr 27 '15 at 13:18
  • It should be done like this: `preg_match_all('/[a-zA-Z0-9]{4,10}/', 'hello', $matches); print_r($matches);` – Wiktor Stribiżew Apr 27 '15 at 13:20
  • I try it: echo "res = "; echo preg_match($pattern, $_POST['username']); But it is howerver empty – all_key_the Apr 27 '15 at 13:22
  • @stribizhev: I try the code that you posted! The result is the same if I use 'hello' and if I use 'hello@'. If I don't put $matches the result is 0 in both. If I put $matches the result is: Array – all_key_the Apr 27 '15 at 13:25
  • its possible that this part of code even not executed due to `Undefined index: username` in `echo "Username = $_POST[username]
    ";`, wrap username with quotes
    – Asgu Apr 27 '15 at 13:26
  • @asgu I edited my code with Username = $_POST['username'] but however it dows not work – all_key_the Apr 27 '15 at 13:40