darth-dev-vader
darth-dev-vader

Reputation: 93

Translate non-digital characters to specific digits

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

Upvotes: 3

Views: 233

Answers (5)

mickmackusa
mickmackusa

Reputation: 47992

To perform a string translation, the most appropriate native function is strtr().

If you don't need to translate to double digit numbers, to can pass two correlated strings.

Code: (Demo)

echo strtr('abcde 5', ' abcde', '012345');
// 1234505

If you need to accommodate the full alphabet, then declare an associative array of string keys to numeric values. The map can be manually written or populated with a variety of native functions.

Code: (Demo)

$map = [];
array_push($map, ' ', ...range("a", "z"));
echo strtr('abcde 5', array_flip($map));
// 1234505

Or as a one-liner:

echo strtr('abcde 5', array_flip(array_merge([' '], range("a", "z"))));

To accommodate uppercase charactets, simply call strtolower() on the input string before translating.

Relevant reading:

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

To use the numbers that you have shown a = 1 etc... then just do a case-insensitive replace:

$result = str_ireplace(range('a', 'z'), range(1, 26), $string);

If you want the ASCII value then split to an array, map to the ord value and join:

$result = implode(array_map(function($v) { return ord($v); }, str_split($string)));

Upvotes: 1

Snickfire
Snickfire

Reputation: 512

Using regex should be like this:

$search  = array('/[A-a]/', '/[B-b]/', '/[C-c]/', '/[D-d]/', '/[" "]/');
$replace = array('1', '2', '3', '4', '5');

$final = preg_replace($search, $replace,"abcd ABCD a55");

echo $final;

Output: 1234512345155

Upvotes: -1

Honk der Hase
Honk der Hase

Reputation: 2488

Here is the complete code:

$s = 'abcde';
$p = str_split($s);
foreach($p as $c) {
    echo ord($c) - ord('a') + 1;
}

Upvotes: 1

Qirel
Qirel

Reputation: 26460

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);
}

Upvotes: 1

Related Questions