开发者

Checking string format with regex in PHP

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,开发者_如何学C} 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?


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');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜