tags:

views:

300

answers:

5

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?

A: 

The best and most flexible way to accomplish that is using regular expressions. But I`m not sure how to do that in PHP but this article can help. link

RHaguiuda
+8  A: 

You can filter it like:

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

As for some symbols, you should be more specific

Sarfraz
+2  A: 

You can test your string (let $str) using preg_match:

if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
    // string only contain the a to z , A to Z, 0 to 9
}

If you need more symbols you can add them before ]

SergeanT
Wait, no delimiter?
Alix Axel
The pattern is wrong, it should be `/^[a-zA-Z0-9]+$/`.
Alix Axel
SergeanT
+1  A: 

Why are those "symbols" in there in the first place? Looks to me like you're reading the text from a source that's encoded as UTF-16, but you're decoding it as something else, such as latin1 or ASCII.

Alan Moore
A: 

Both these regexes should do it:

$str = preg_replace('~[^a-z0-9]+~i', '', $str);

Or:

$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
Alix Axel