phpstringasciinumericstring-conversion

Converting a string of letters to a string of numbers in PHP


I'm trying to write a PHP function that converts a string of letters to a corresponding string of numbers.

For example, the input abc should return 123 and the input wxyz should return 23242526. I have done some research and found that the ord function can be used to get the ASCII value of a character, but, i'm not sure how to use it.

Is there a way to use the ord function or another built-in PHP function to accomplish this task efficiently? If not, what is the best way to write a custom function for this purpose?

For example:

<?php   
convert_letters_to_numbers('abc') => 123
convert_letters_to_numbers('wxyz') => 23242526

Solution

  • <?php
    function convertletternums($str)
    {
        $result = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $result .= ord($str[$i]) - 96;
        }
        return $result;
    }
    

    This function takes 1 string as input and returns numbers as output.

    To work, this function converts each character in the input string to a number using the ord function, which returns the ASCII value of a character. The ASCII value of a lowercase letter is its position in the alphabet (for example a = 97, b = 98, etc.), so subtracting 96 from this value gives us the desired result (a = 1, b = 2, etc.). The function combines the numerical values and returns the result as a single string.

    Few examples of how this function can be used:

    echo convertletternums('abc');  // Outputs: 123
    echo convertletternums('wxyz'); // Outputs: 23242526
    echo convertletternums('hello'); // Outputs: 8541215121215