1

I have some string in which I would like to check if contains some letters or numbers. Those letters are from a-z, A-Z and all numbers.

So this is the example: $goodstring = "abcdefg%$#%&asdqwe"; $badstring = "%$#&%#/&/#$%!#-.";

check if $goodstring contains letters/numbers and if, then return true. check if $badstring contains letters/numbers and if not, then return false.

I have also used preg_match, but this works only if there are not some letters/numbers in string.

user1257255
  • 1,161
  • 8
  • 26
  • 55
  • you want to check if the string contains only letters a-z, A-Z and numbers or you want to check if it contains at least one of those? – Ivaylo Strandjev Apr 20 '12 at 07:44
  • **I have also used preg_match**. You might've done it wrong. Why not share what you tried? – Nanne Apr 20 '12 at 07:46
  • I want check if contains any letter/number - it's not important if there is one or more, just shouldn't contains characters %$#!& I tried this, but don't work good: preg_match("/^([a-zA-Z0-9])+$/i", $badstring) – user1257255 Apr 20 '12 at 07:46
  • @user1257255 so you want to check if it contains ONLY alphanumerics? – Ivaylo Strandjev Apr 20 '12 at 07:53

2 Answers2

2

Here you go ("only" version):

$containsOnlyLettersOrNumbers = (preg_match('~^[0-9a-z]+$~i', $string) > 0);

Or (depending on what you want exactly):

$containsLettersOrNumbers = (preg_match('~[0-9a-z]~i', $string) > 0);
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
-1
var_dump(preg_match('#[0-9]|[a-z]#i', $goodstring));
var_dump(preg_match('#[0-9]|[a-z]#i', $badstring));
s.webbandit
  • 16,332
  • 16
  • 58
  • 82