Link to home
Start Free TrialLog in
Avatar of MeridianManagement
MeridianManagementFlag for United States of America

asked on

Filter a string in PHP for Alpha Numeric Only. Complex String?

Sorry, this is a really beginner question, but if I have a string that has some characters like new lines and random things and I only want numbers and letters, how do I filter everything else out in PHP?

I know it's a regular expression, probably something like /[A-Za-z0-9]/ or something but I don't know exactly what commands to use.
Avatar of HuyBD
HuyBD
Flag of Viet Nam image

try with
[a-zA-Z0-9]+
Avatar of MeridianManagement

ASKER

What function do I use? preg_match?

Let's say I have $string and I want to do end up with $result, can you show me the PHP commands?
ASKER CERTIFIED SOLUTION
Avatar of HuyBD
HuyBD
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
preg_match_all('/[a-zA-Z0-9]+/', $string,$matcharray);
$result = implode(' ',$matcharray[0]);

This answers your question directly, from $string to $result.  Don't give me any points though, HuyBD did the work :)
SOLUTION
Avatar of ddrudik
ddrudik
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you, I think this will work great. I know this isn't part of the original question, but can you guys tell me how to incorporate acceptable special characters into the regular expression? Such as a - or a (
oh, and a space! how do you do that?
Instead of [^A-Z0-9] you would use [^A-Z0-9( -] if that's what you are asking.  Put the dash last in the character set or escape it with a \ character.