PHP. How to Check If String Contains Only Specific Characters

The following function checks if a string contains only specified characters. The allowed characters are passed as a string. It is designed not to use Regular Expressions. It uses the function mb_str_to_array and is Unicode aware. Note. If an empty string is passed the function will return true.

//======================== START OF FUNCTION ==========================//
// FUNCTION: str_contains_only                                         //
    * Checks whether a string contains only characters specified in the gama.
    * @param String $string
    * @param String $gama
    * @return boolean
function str_contains_only($string,$gama){
    $chars = mb_str_to_array($string);
    $gama = mb_str_to_array($gama);
    foreach($chars as $char) {
        if(in_array($char, $gama)==false)return false;
    return true;
//  FUNCTION: str_contains_only                                        //
//========================= END OF FUNCTION ===========================//

Example 1. Check for Vowels Only

In this small example we will check if the string contains only vowels.

$string = "An example string";

$vowels = "aeiouAEIOU";

if (str_contains_only($string, $vowels) == false) {
    echo "Please, use only vowels...";

Example 2. Check Username for Invalid Characters

This example checks a user's username for invalid characters. The allowed characters are small and capital Latin characters, numbers and dashes.

$username = "My SuperDuper UserName_2014";

$lower_case = "abcdefghijklmnopqrstuvwxyz";
$upper_case = strtoupper($lower_case);
$numbers = "0123456789";
$dashes = "_-";
$allowed = $lower_case.$upper_case.$numbers.$dashes;

if (str_contains_only($username, $allowed) == false) {
    echo "Please, use only lower and upper case characters, numbers and dashes...";

Example 3. Check Post for Cyrillic Letters Only

This example checks if only Cyrillic letters are used in text posted by a user (i.e. on forum where Cyrillic is used as primary alphabet). If characters, which are not allowed by the administrator are used, it will prompt the user to use the allowed characters only.

$post = trim($_POST['user_post']);

$lower_case = "абвгдежзийклмнопрстуфхцчшщьъюя";
$upper_case = strtoupper($lower_case);
$numbers = "0123456789";
$special = "!@#$%^&*()_-=+{}[]'.;:?"; // Define special chars
$allowed = $lower_case.$upper_case.$numbers.$special;

if (str_contains_only($post, $allowed) == false) {
    echo "Please, use only Cyrillic letters in this forum...";