Johan
Johan

Reputation: 19072

How to get A-Z and 0-9 from a string?

How do I get "Lrumipsm1" from "Lörum ipsäm 1!"?

So what I need is to only get a-z and 0-9 from a string, using php.

Upvotes: 0

Views: 722

Answers (2)

ghostdog74
ghostdog74

Reputation: 342649

you can do this also

$in = "Lörum ipsäm 1!";
$result = preg_replace('/[^[:alnum:]]/i', '', $in);
echo $result;

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

E.g. by using a regular expression (pcre) and replacing all characters that are not within the class of "acceptable" characters by ''.

$in = "Lörum ipsäm 1!";
$result = preg_replace('/[^a-z0-9]+/i', '', $in);
echo $result;

see also: http://docs.php.net/preg_replace

edit:
[a-z0-9] is the class of all characters a....z and 0...9
[^...] negates a class, i.e. [^a-z0-9] contains all characters that are not within a...z0...9
+ is a quantifier with the meaning "1 or more times", [^a-z0-9]+ matches one or more (consecutive) characters that are not within a...z0..9.
The option i makes the pattern case-insensitive, i.e. [a-z] also matches A...Z

Upvotes: 7

Related Questions