How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
+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
2010-05-24 11:10:01
+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
2010-05-24 11:14:40
Wait, no delimiter?
Alix Axel
2010-05-24 12:13:02
The pattern is wrong, it should be `/^[a-zA-Z0-9]+$/`.
Alix Axel
2010-05-24 17:32:57
SergeanT
2010-05-24 19:35:14
+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
2010-05-24 12:10:27
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
2010-05-24 12:15:08