Mike Rogers on a Snowmobile

PHP's Ctype Functions

Posted on

A few days ago I was researching methods of validating alphanumeric strings and I was shown PHPs Ctype Functions by Sebastian Roming.

In a nutshell they are a group of PHP functions why can be used to check strings to see if they are alphanumeric, numeric etc without using regex (So they are fast!). The key thing to remember is that they return TRUE or FALSE, unlike filter_var which returns FALSE or the string.

Here is the code example:

<?php
// Check if input is alphanumeric (letters and numbers)
ctype_alnum('abcdef1234'); // This returns TRUE
ctype_alnum('£%^&ab2'); // This on the otherhand returns FALSE

// check if input is alpha (letters)
ctype_alpha('dssfsdf'); // returns TRUE
ctype_alpha('12345dssfsdf'); // Returns FALSE
?>
View on Gist Github

It also contains functions to check for just numeric strings, uppercase strings and lowercase strings.

<?php
// Check if the input is numeric
ctype_digit('1234'); // TRUE
ctype_digit('1as2d34f'); // FALSE

// Uppercase
ctype_upper('HELLO'); // TRUE
ctype_upper('hElLo'); // FALSE

// Lowercase
ctype_lower('hello'); // TRUE
ctype_lower('HeLLo'); // FALSE
?>
View on Gist Github

Handy right?

This was written by Mike Rogers, a freelance Ruby on Rails developer based in London.

Share the ♥ by sharing this!

If you want to discuss this post, feel free to tweet me (@MikeRogers0) or drop me an email. Any code samples unless stated otherwise are licensed under the The MIT License (MIT). Spotted a mistake? Send me a pull request :)