ctype_alnum

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_alnumAuf alphanumerische Zeichen überprüfen

Beschreibung

ctype_alnum ( mixed $text ) : bool

Gibt true zurück, wenn alle Zeichen in text entweder ein Buchstabe oder eine Ziffer sind. Anderenfalls wird false zurückgegeben.

Parameter-Liste

text

Der zu prüfende String.

Hinweis:

Wenn ein int zwischen -128 und 255 (inklusive) übergeben wird, wird dieser als ASCII-Wert eines einzelnen Buchstabens interpretiert (zu negativen Werten wird 256 dazu addiert, um Buchstaben des erweiterten ASCII-Zeichensatzes zu erlauben). Alle anderen Integer werden wie eine Zeichenkette interpretiert, welche die dezimalen Ziffern des Integers enthält.

Rückgabewerte

Liefert true wenn jedes Zeichen in text ein Buchstabe oder eine Ziffer ist, sonst false.

Beispiele

Beispiel #1 ctype_alnum() Beispiel (standard-locale vorausgesetzt)

<?php
$strings 
= array('AbCd1zyZ9''foo!#$bar');
foreach (
$strings as $testcase) {
    if (
ctype_alnum($testcase)) {
        echo 
"Der String $testcase enthält nur Buchstaben und Ziffern.\n";
    } else {
        echo 
"Der String $testcase besteht nicht nur aus Buchstaben und Ziffern.\n";
    }
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Der String AbCd1zyZ9 enthält nur Buchstaben und Ziffern.
Der String foo!#$bar besteht nicht nur aus Buchstaben und Ziffern.

Siehe auch

add a note add a note

User Contributed Notes 4 notes

up
83
thinice at gmail dot com
14 years ago
ctype_alnum() is a godsend for quick and easy username/data filtering when used in conjunction with str_replace().

Let's say your usernames have dash(-) and underscore(_) allowable and alphanumeric digits as well.

Instead of a regex you can trade a bit of performance for simplicity:

<?php
$sUser
= 'my_username01';
$aValid = array('-', '_');

if(!
ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo
'Your username is not properly formatted.';
}
?>
up
16
Anonymous
11 years ago
Quicktip: If ctype is not enabled by default on your server, replace ctype_alnum($var) with preg_match('/^[a-zA-Z0-9]+$/', $var).
up
3
marcelocamargo at linuxmail dot org
8 years ago
It is also important to note that the behavior of `ctype_alnum` differs according to the operating system. For UNIX-based operating system, if you pass a value that is not a string (or an overloaded object), independently of the value, it will always result in false. However, if we do the same on Windows, using, for example, -1 as literal (a minus and a number greater than 0), we'll have true as result.

<?php var_dump(ctype_alnum(-1));
// UNIX: bool(false)
// Windows: bool(true)
up
-7
Rory
14 years ago
Just for the record, Gentoo doesn't include this function by default. You'll have to recompile PHP with the "ctype" USE flag.
To Top