Patrick Pierson
Patrick Pierson

Reputation: 107

replacing letters with numbers

So i've been trying to get this bit of code to work all day and haven't been able to do it... I wnat to be able to replace letters with a number (or just a value) from an array. this is the code i've got:

    $l2n = 
    array(
            'a'=>'1',
            'b'=>'2',
            'c'=>'3',
            'd'=>'4',
            'e'=>'5',
            'f'=>6,
            'g'=>7,
            'h'=>8,
            'i'=>9,
            'j'=>10,
            'k'=>11,
            'l'=>12,
            'm'=>13,
            'n'=>14,
            'o'=>15,
            'p'=>16,
            'q'=>17,
            'r'=>18,
            's'=>19,
            't'=>20,
            'u'=>21,
            'v'=>22,
            'w'=>23,
            'x'=>24,
            'y'=>25,
            'z'=>16
            );
$string = str_split($string);
$explode = array_shift($string);
if($l2n[$explode] == $explode)
{
    echo $l2n[$explode];
}
else
{
    echo $l2n['a'];
}

I tried to use Preg_replace but i've never had a good expereince with that function. so If anybody could help me out, hint me in the correct direction, that'd be great.

Upvotes: 0

Views: 271

Answers (3)

scrowler
scrowler

Reputation: 24406

You can just use str_replace once you've used array_keys and array_values to get each side of the array:

$keys = array_keys($l2n);
$values = array_values($l2n);

$yourstring = 'Hello world!';

echo str_replace($keys, $values, $yourstring);

// H5121215 231518124!

Demo: https://eval.in/77453

Docs:

Upvotes: 2

Maciej Sz
Maciej Sz

Reputation: 12035

Why in the world would you use an array for this? Isn't ord() what you are looking for here?

$string = "ABCDE";

foreach ( str_split($string) as $chr ) {
    echo ord($chr) - 64; // or 97 if they all are lowercase
    echo PHP_EOL;
}

Upvotes: 0

Francisco Presencia
Francisco Presencia

Reputation: 8851

You can simply do:

$string = preg_replace(array_keys($l2n), array_values($l2n), $string);

From the documentation:

If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart.

Upvotes: 1

Related Questions