Question

I want to use php preg_replace to remove (note that i want them removed, so i dont want to use htmlentities)

I want to allow the charecters a-z, A-Z, 0-9, and the special chars "@_." only

Was it helpful?

Solution

Pretty straight-forward:

$string = preg_replace('/[^a-zA-Z0-9@.]+/', '', $string);

In simple English: Replace one or more occurrences of anything that's not an alphabet, number or the symbol @, ., with nothing.

Autopsy:

  • / - starting delimiter
  • [^a-zA-Z0-9@.] - a character class
    • ^ - used to negate the character class
    • a-zA-Z0-9 - alphabets or numbers
    • @ - literal character @
    • . - literal character .
  • + - match the previous quantity one or more times
  • / ending delimiter
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top