zuk1
zuk1

Reputation: 18389

Check if string only contains alphanumeric and dot characters

I need to check to see if a variable contains anything OTHER than a-z, A-Z, 0-9 and the . character (full stop).

Upvotes: 4

Views: 14369

Answers (4)

mickmackusa
mickmackusa

Reputation: 48073

If you don't want to wheel out the regex engine, you can ltrim the string by the whitelisted characters, then check if the string is empty.

Yes, the trim() functions allow character ranges to be expressed via "yatta-yatta" dots. Read more about it at Native PHP functions that allow double-dot range syntax.

Code: (Demo)

if (ltrim($str, 'A..Za..z0..9.') !== '') {
    // all good
}

Upvotes: 1

maxnk
maxnk

Reputation: 5745

if (preg_match("/[^A-Za-z0-9.]/", $myVar)) {
   // make something
}

The key point here is to use "^" in the [] group - it matches every character except the ones inside brackets.

Upvotes: 8

ʞɔıu
ʞɔıu

Reputation: 48446

There are two ways of doing it.

Tell whether the variable contains any one character not in the allowed ranges. This is achieved by using a negative character class [^...]:

preg_match('/[^a-zA-Z0-9\.]/', $your_variable);

Th other alternative is to make sure that every character in the string is in the allowed range:

!preg_match('/^[a-zA-Z0-9\.]*$/', $your_variable);

Upvotes: 10

PEZ
PEZ

Reputation: 17004

if (preg_match('/[^A-Z\d.]/i', $var))
  print $var;

Upvotes: 8

Related Questions