YeuSeChia YeuSeChia - 4 months ago 13
PHP Question

How to replace a string with data, from 2 arrays?

I have 2 arrays:

$arrayOne = array (

"1" => "a",
"7" => "e",
"5" => "c",
"4" => "x",
"2" => "r"

);


and

$arrayTwo = array (

"7" => "k",
"9" => "z",
"1" => "y",
"3" => "x",
"2" => "b"

);


In these arrays, keys are numbers.




I have a simple string:
$stringInp = "There is my text.";
.

I want to replace
$stringInp
with values from
$arrayOne
, by values from
$arrayTwo
. There is my idea:


  • Step 1. If there is a group of letter in
    $stringInp
    (what is existed in
    $arrayOne
    ), search in
    $arrayTwo
    what value is attached which the same key (what is existed in
    $arrayOne
    ).

  • Step 2. Replace all existed values (from Step 1.), with this function:
    strtr();
    .

  • Step 3. Display new output string (which is replaced completely, from Step 2.).



The output string is:
$stringOut = "Thkrk is my tkxt.";
.




How to create a simple PHP function, that it will do it like this?

Answer

First we need to use array_intersect_key, to find keys which present in both arrays.

Second we sort intersected arrays so their keys were in same order with ksort.

Third we use array_combine to create second parameter for strtr function.

Forth we use strtr:

$arrayOne = array (
    "1" => "a",
    "7" => "e",
    "5" => "c",
    "4" => "x",
    "2" => "r"
);

$arrayTwo = array (
    "7" => "k",
    "9" => "z",
    "1" => "y",
    "3" => "x",
    "2" => "b"
);

$keys = array_intersect_key($arrayOne, $arrayTwo);
ksort($keys);
$values = array_intersect_key($arrayTwo, $arrayOne);
ksort($values);

echo strtr('There is my text.', array_combine($keys, $values));

Update: for older versions try:

$replace = array();
foreach ($arrayOne as $k => $v) {
    // use isset if you want to replace something with empty string
    if (!empty($arrayTwo[$k])) {    
        $replace[$v] = $arrayTwo[$k];
    }
}

echo strtr('There is my text.', $replace);