Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to enforce alpha-numeric but allow apostrophes and hyphens?

Tags:

regex

php

How would I alter this function so that it allows single apostrophe's and hyphens:

function sanitize_string($s) {
    $result = preg_replace("/[^a-zA-Z0-9]+/", " ", html_entity_decode($s, ENT_QUOTES));
    return $result;
}
like image 235
Scott B Avatar asked Apr 15 '11 12:04

Scott B


2 Answers

Just include the single apostrophe and the 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;
}
like image 104
halfdan Avatar answered Nov 01 '22 05:11

halfdan


Trying to get an answer to you as quick as I can.

I think you can just add them into the character class; possibly you'll need to escape them though.

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

like image 36
Keng Avatar answered Nov 01 '22 04:11

Keng