q0987
q0987

Reputation: 35982

Question about regular expressions

I saw this statement

$name = ereg_replace("[^A-Za-z0-9.]", "", $name);

What is the difference between [^A-Za-z0-9.] and [A-Za-z0-9.]?

Based on my understanding of regular expression, the [] is used to include all valid characters for replacment in function ereg_replace.

Then what is the purpose of including ^ into the []?

Thank you

Upvotes: 1

Views: 84

Answers (1)

Gumbo
Gumbo

Reputation: 655319

The initial ^ inside a character class […] inverts the set of characters that are described inside the character class. While [A-Za-z0-9.] matches one character of the character set described by A-Za-z0-9., [^A-Za-z0-9.] matches any other character except one of the characters described by A-Za-z0-9.. What these other characters are depends on the base character set the string is defined with.

So [abc] matches either a, b, or c and [^abc] matches any other character except a, b, and c. Your example code will remove any characters that are not described by [A-Za-z0-9.]. That leaves only characters of [A-Za-z0-9.].

Upvotes: 11

Related Questions