Showing posts with label PHP ctype_lower. Show all posts
Showing posts with label PHP ctype_lower. Show all posts

Friday, 19 September 2014

PHP: Check if a string contains only alphabetic lowercase characters

<?php

/**
 * Example for ctype_lower() function usage 
 * checks if a string contains only lowercase alphabetic characters
 */
//$exampleStrings is an array with different strings that needs to be tested
echo '<!DOCTYPE html>
<html>
    <head>
        <title>example</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
     <body>
        <center>';
$exampleStrings = array('pingponG', 'ferrari', 'ret233');
foreach ($exampleStrings as $string) {
    if (ctype_lower($string)) {
        //if the $string contains only lowercase alphabetic charcaters display the message bellow
        echo '<br /><div style="background-color:green;color:#fff;padding:10px;width:400px;font-size:16px">
        The string <b>' . $string . '</b> consists of all lowercase alphabetic characters</div><br />';
    } else {
        //if the $string does not contains only control charcaters display the message bellow
        echo '<br /><div style="background-color:red;color:#fff;padding:10px;width:400px;font-size:16px">
        The string <b>' . $string . '</b> does not consist of all lowercase alphabetic characters
        </div><br />';
    }
}
echo '</center>
    <body>
</html>';
?>


The string pingponG does not consist of all lowercase alphabetic characters


The string ferrari consists of all lowercase alphabetic characters


The string ret233 does not consist of all lowercase alphabetic characters

PHP function to check string if is all lowercase



ctype_lower:
This can be used to check for lowercase character(s)

Syntax:
bool ctype_lower ( string $text )

Parameter:
text:The tested string.

Return value:
Returns TRUE if every character in text is a lowercase in the current locale.


<?php/* simple code shippet for check_lowercase_string
function check_lowercase_string($string) {
    return ($string === strtolower($string));
}
*/


//created function with full analysis(it is created instead of built in function.)
function check_lowercase_string($string) {
    $chars = '';
    // map all small chars
    for($alpha = 'a'; $alpha != 'aa'; $alpha++) { $small[] = $alpha; }
    $l = 0; // not strlen() :p
    while (@$string[$l] != '') {
        $l++;
    }
    for($i = 0; $i < $l; $i++) { // for each string input piece
        foreach($small as $letter) { // for each mapped letter
            if($string[$i] == $letter) {
                $chars .= $letter; // simple filter
            }
        }
    }

    // if they are still equal in the end then true, if they are not, false
    return ($chars === $string);
}
 





$string = 'Hi! I am a string';
var_dump(check_lowercase_string($string));  //false
$string = 'string';
var_dump(check_lowercase_string($string));  //true

?>