Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to return only alpha-numeric characters from string?

Tags:

regex

php

I'm looking for a php function that will take an input string and return a sanitized version of it by stripping away all special characters leaving only alpha-numeric.

I need a second function that does the same but only returns alphabetic characters A-Z.

Any help much appreciated.

like image 458
Scott B Avatar asked Mar 04 '11 20:03

Scott B


People also ask

How do you select only alphanumeric characters from a string in Python?

To check if given string contains only alphanumeric characters in Python, use String. isalnum() function. The function returns True if the string contains only alphanumeric characters and False if not.

How do you find the alphanumeric of a string?

The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.

How do you separate numbers from alphanumeric strings?

Extract Numbers from String in Excel (using VBA) Since we have done all the heavy lifting in the code itself, all you need to do is use the formula =GetNumeric(A2). This will instantly give you only the numeric part of the string.

How do you remove everything except alphanumeric characters from a string?

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .


1 Answers

Warning: Note that English is not restricted to just A-Z.

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s); 

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

Try this to leave only A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s); 

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.

like image 95
Mark Byers Avatar answered Nov 13 '22 03:11

Mark Byers