Is it possible to convert characters in a string into specific numbers like
a = 1, // uppercase too
b = 2,
c = 3,
d = 4,
e = 5, // and so on til letter 'z'
space = 0 // I'm not sure about if space really is equals to 0
Here's how I think it goes.
$string_1 = "abed"; // only string
$string_2 = "abed 5"; // with int
$result_1 = convert_to_int($string_1); // output is 1254
$result_2 = convert_to_int($string_2); // output is 125405
Create an array, and insert a space to the first element. Then use range()
to generate an array with a
to z
. Use strtolower()
to force the input to lowercase (as the characters from range()
we generate is lowercase too.
Then do a replacement with str_replace()
, which accepts arrays as values. The keys is the value that the value will be replaced with.
function convert_to_int($string) {;
$characters = array_merge([' '], range('a', 'z'));
return str_replace(array_values($characters), array_keys($characters), $string);
}