Without use strtolower function how to convert string lowercase in PHP


#1

How to convert string all characters lower case without use built in function strtolower?

Please give me advise.


#2
$my_str = "SOME STRING";
$temp_str = "";
for ($i = 0; $i < strlen($my_str); $i++) {
    $char_code = ord($my_str[$i]);
    if ($char_code > 64 && $char_code < 92) {
        $temp_str = $temp_str . chr($char_code + 32);
    } else {
        $temp_str = $temp_str . $my_str[$i];
    }
}
$my_str = $temp_str;
print "$my_str\n";
// -> some string

https://repl.it/KgOl


#3

Thanks for your help.


#4

@mtf want to ask something in this code. If you have time please tell me sir

ord and chr without use how to edit in this code.


#5

Not sure I get your question. Above I wrote a rudimentary “program” that modifies only characters of the alphabet that are uppercase. The ord() function was necessary to identify those characters. The chr() function was necessary in the replacement of those characters with their lowercase equivalent. How I would do this without those two functions will take some more thought.

There is, of course a character map approach. We could build an associative array that contains all the letters of the alphabet as keys, and their corresponding alternate case as values.

$str_lower = array(
    'A' => 'a',
    'B' => 'b',
    'C' => 'c',
    // ...
);
$str_upper = array(
    'a' => 'A',
    'b' => 'B',
    'c' => 'C',
    // ...
);

Now you simply iterate over your text and match with keys in the appropriate table to find the substitute value.

Bear in mind that string objects are not mutable. We modify them by replacing them with the modified form, which is what string functions are designed to help with.


#6

Thanks you very much for your reply.


#7
$temp_str = "";
for ($i = 0; $i < strlen($my_str); $i++) {
    $key = $my_str[$i];
    if (array_key_exists($key, $str_lower)) {      // or $str_upper
        $temp_str = $temp_str . $str_lower[$key];  // or $str_upper[$key]
    } else {
        $temp_str = $temp_str . $key;
    }
}
$my_str = $temp_str;
print "$my_str\n";
SOME STRING
some string

https://repl.it/KgOl/1


#8

Going a step further,

function set_case($str, $flag) {
    global $str_lower, $str_upper;
    $temp_str = "";
    $case = $flag ? $str_upper : $str_lower;
    for ($i = 0; $i < strlen($str); $i++) {
        $key = $str[$i];
        if (array_key_exists($key, $case)) {
            $temp_str = $temp_str . $case[$key];
        } else {
            $temp_str = $temp_str . $key;
        }
    }
    return $temp_str;
}
$upper = set_case($my_str, true);
print "$upper\n";                    // -> SOME STRING
$lower = set_case($my_str, false);
print "$lower\n";                    // -> some string

https://repl.it/KgOl/2