Frank
Frank

Reputation: 1864

PHP remove everything except letters and a hyphen (-)

I'm making a form that asks for the user's first and last name, and I don't want them entering

$heil4

I would like them to enter

Sheila

I know how to filter out everything except letters, but I'm aware that some names can have

Sheila-McDonald

So how would I remove everything from a string apart from letters and a hyphen?

Upvotes: 5

Views: 3664

Answers (4)

Ωmega
Ωmega

Reputation: 43673

Simply use

$s = preg_replace("/[^a-z-]/i", "", $s);

or if you want to convert some non-ascii characters to ascii, such as Jean-Rémy to Jean-Remy, then use

$s = preg_replace("/[^a-z-]/i", "", iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s)); 

Upvotes: 7

Alex
Alex

Reputation: 12029

$new = preg_replace('#[^A-Z-]#iu', '', $data);

but instead of removing letters (and thus modifying user's input) better validate it and show an error if the input is not valid. This way the user will know that what he had entered is exactly the value you have

if(!preg_match('#[A-Z-]#iu', $data)) echo 'invalid';

Upvotes: 2

Eamonn
Eamonn

Reputation: 1320

Use this to strip out all non alpha-numeric characters, not including non latin characters, and prescribed punctuation.

$strtochange= preg_replace("/[^\s\p{Pd}a-zA-ZÀ-ÿ]/",'',$strtochange);

Note: this will turn $heil4 into heil.

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Instead of replacing with nothing, have some fun. that way a name that consists mainly of numbers you can decode ;p

$name = '$h3il4-McD0nald';

$find    = array(0,1,3,4,5,6,7,'$');
$replace = array('o','l','e','a','s','g','t','s');
$name = str_replace($find,$replace,$name);

//Sheila-McDonald
echo ucfirst(preg_replace('/[^a-z-]/i', '', $name));

Upvotes: 2

Related Questions