tags:

views:

75

answers:

2

I have been trying to use preg_match with "/^[a-zA-Z0-9_-]+$/" trying to make sure that the string given only contained the characters there and nothing else, but it seems to not be counting the $ properly so that it matches all the way to the end of the line, but it does require the match at the start of the string using ^.

If I use {3,} instead of +: "/^[a-zA-Z0-9_-]{3,}$/" which is how I had it at first, I could write 3 letters/numbers, - or _ and then any character other than those and it would count it as a match.

code:

  if(preg_match("/^[a-zA-Z0-9_-]+$/", $value, $arr) && strlen($value) > 3)
  {
   echo $good .' Ok';
  }
  else
  {
   echo $bad .' Invalid username. (letters & numbers only)';
  }

using things like the following as $value, it tells me it is ok when it should be coming up as invalid username because of the space or & characters.

word word

word&word

And it turns out it was because the values were being sent to the page through $_GET and $value of something such as "word&word" came up as "word" instead... is there a way to fix that?

A: 

And it turns out it was because the values were being sent to the page through $_GET and $value of something such as "word&word" came up as "word" instead... is there a way to fix that?

You'll need to encode the ampersand in the URL:

[url]/script.php?string=word&word

becomes

[url]/script.php?string=word&word

Try using urlencode if the link's being generated by PHP.

Edit Or try using _POST instead.

Pete
+2  A: 

And it turns out it was because the values were being sent to the page through $_GET and $value of something such as "word&word" came up as "word" instead... is there a way to fix that?

I'm throwing a wild guess here that your PHP page that you call from browser as http://yoursite/page.php?something=word&word is reading $_GET['something'] to be word instead of your expected word&word.

Well, this is because literal ampersand symbol is treated as $_GET parameters delimiter and any ampersand symbol that you want to include in a parameter value must be url-encoded as %26, as in http://yoursite/page.php?something=word%26word . In PHP, you can use function urlencode() to encode your string values:

$url = 'http://yoursite/page.php?something=' . urlencode('word&word');
Lukman
The footnote to this is the `$_GET` and `$_POST` are automatically urldecoded, so there's no need to `urldecode()` manually on the other side.
Peter Ajtai