riad
riad

Reputation: 7194

Match string using preg_match

I have text in a $abc variable.

Now I want to check that text can hold only characters (a-z, A-Z, 0-9). If they have any character except those, then "a output" should be returned.

How can I do that?

example: $abc = "this is @ text"; // no match 

Upvotes: 1

Views: 566

Answers (3)

Yoshi
Yoshi

Reputation: 54649

Something like:

$abc = "this is @ text";
if (!preg_match('/^[a-z0-9]*\z/i', $abc)) {
  echo 'bad';
}

With regards to Jame C's comment, here is the inverted case:

$abc = "this is @ text";
if (preg_match('/[^a-z0-9]/i', $abc)) {
  echo 'bad';
}

Upvotes: 6

James C
James C

Reputation: 14149

you should be able to evaluate

preg_match('/[^A-Za-z0-9]/', $myString)

if you don't mind spaces and underscores being in there too then you could use this:

preg_match('/\W/', $myString)

Upvotes: 2

binaryLV
binaryLV

Reputation: 9122

if ( !preg_match('#^[a-zA-Z0-9]*$#', $abc) ) {
    // wrong chars spotted
}

Upvotes: 4

Related Questions