-3

Hey guys i want to convert a string from lowercase to uppercase and vice versa without using any built in functions strtoupper or strtolower in php, can anyone help me please.

edit: I can use some other functions to do the job, like substr(), ord(), chr(), strlen(), str_replace.

This was my first question here so could not specify what i needed in best way. I was given task to do the job in these mentioned functions without use of arrays either.

...next time i will be careful.

zniz
  • 95
  • 1
  • 8

4 Answers4

3

the c functions look like:

PHPAPI char *php_strtoupper(char *s, size_t len)
{
    unsigned char *c, *e;

    c = (unsigned char *)s;
    e = (unsigned char *)c+len;

    while (c < e) {
        *c = toupper(*c);
        c++;
    }
    return s;
}

PHPAPI char *php_strtolower(char *s, size_t len)
{
    unsigned char *c, *e;

    c = (unsigned char *)s;
    e = c+len;

    while (c < e) {
        *c = tolower(*c);
        c++;
    }
    return s;
}

but also these functions use tolower and toupper from ctype.h C library! look at the souce here

bitWorking
  • 12,485
  • 1
  • 32
  • 38
2
function myStrToLower($string) {
    $from = range('A','Z');
    $to = range('a','z');
    return str_replace($from, $to, $string);
}

function myStrToUpper($string) {
    $from = range('a','z');
    $to = range('A','Z');
    return str_replace($from, $to, $string);
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

while I can not imagine why you would want to do this; you may consider making an array matching the lowercase to the uppercase of each letter. Then for every character in the string, find it in this array and return the value. (or the key if you are going the other direction).

While built in functions have overhead, I think this method will incur more overhead still.

EDIT: alternatively, you could convert each character to ascii then check the range to see if it is upper or lowercase. Then add or subtract 32 (dec) to change to the other case.

NappingRabbit
  • 1,888
  • 1
  • 13
  • 18
0

One possible implementation (if you allow for str_split) would be:

function myToLowerCase( $str )
{
    static $charMap = array(
        'A' => 'a', 'B' => 'b', 'C' => 'c', 'D' => 'd', 'E' => 'e', 'F' => 'f',
        'G' => 'g', 'H' => 'h', 'I' => 'i', 'J' => 'j', 'K' => 'k', 'L' => 'l',
        'M' => 'm', 'N' => 'n', 'O' => 'o', 'P' => 'p', 'Q' => 'q', 'R' => 'r',
        'S' => 's', 'T' => 't', 'U' => 'u', 'V' => 'v', 'W' => 'w', 'X' => 'x',
        'Y' => 'y', 'Z' => 'z',
    );
    $chars = str_split( $str );
    $result = '';

    for ( $i = 0; $i < count( $chars ); $i++ )
    {
        if ( isset( $charMap[$chars[$i]] ) )
        {
            $result .= $charMap[$chars[$i]];
        }
        else
        {
            $result .= $chars[$i];
        }
    }

    return $result;
}

The uppercase equivalent should be obvious from looking at the example.

Andreas Hagen
  • 2,335
  • 2
  • 19
  • 34