【问题标题】:Converting a string of letters to a string of numbers in PHPConverting a string of letters to a string of numbers in PHP
【发布时间】:2022-12-27 00:55:05
【问题描述】:
Is there a PHP function to turn a string of letters into a string of numbers ?
For example:
<?php
convert_letters_to_numbers('abc') => 123
convert_letters_to_numbers('wxyz') => 23242526
【问题讨论】:
标签:
php
string
ascii
numeric
string-conversion
【解决方案1】:
<?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