Regular expression to provide alphanumeric values, but allow apostrophes and hyphens?

How can I change this function so that it allows using one apostrophe and hyphen:

function sanitize_string($s) {
    $result = preg_replace("/[^a-zA-Z0-9]+/", " ", html_entity_decode($s, ENT_QUOTES));
    return $result;
}
+5
source share
2 answers

Just include a single apostrophe and hyphen at the end of the range:

function sanitize_string($s) {
    $result = preg_replace("/[^a-zA-Z0-9'-]+/", " ", html_entity_decode($s, ENT_QUOTES));
    return $result;
}
+9
source

Trying to get an answer to you as soon as possible.

I think you can just add them to a character class; perhaps you need to run away from them, though.

Note: to use -, be sure to put it at the end, otherwise it will be considered a metacharacter.

+1
source

All Articles