2

I have the following array

static public $tabla = array(
            'A'=>2, 'B'=>2, 'C'=>2,
            'D'=>3, 'E'=>3, 'F'=>3,
            'G'=>4, 'H'=>4, 'I'=>4,
            'J'=>5, 'K'=>5, 'L'=>5,
            'M'=>6, 'N'=>6, 'O'=>6,
            'P'=>7, 'Q'=>7, 'R'=>7,
            'S'=>8, 'T'=>8, 'U'=>8,
            'V'=>9, 'W'=>9, 'X'=>9,
            'Y'=>0, 'Z'=>0
            );

And several strings consisting of alphanumeric characters, for example: "G20513F4561B". What is most efficient way of replacing the non-numeric characters in string by its equivalence according the given array?

I know this can be easily implemented using a loop but maybe there is some kind of regular expression that does the trick.

Thanks

1
  • I think you've almost written a regular expression to do what you want. Replace this with this, replace this with this ... Commented Oct 3, 2012 at 18:29

2 Answers 2

6

You can do that very easily with str_replace, which accepts arrays as its first and second arguments:

echo str_replace(array_keys($tabla), array_values($tabla), $str);

This creates one array containing all the keys from the original array and another containing all the values. The elements are in corresponding positions according to the order of the original array. When str_replace is called with array arguments, the string in the first element of the first array is replaced by the first element of the second array, and so on.

Sign up to request clarification or add additional context in comments.

Comments

2

Try strtr():

echo strtr($str, self::$tabla);

Keys will be replaced with their corresponding values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.