Reputation: 81
Here I created Hashmap array in PHP. I gave input as $keys = str_split('cat1hen')
which give output 'doga@nt
'.
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$keys = str_split('cat1hen');
$output = [];
array_walk($keys,
function($item, $index) use($rule,$keys, &$output) {
if($rule[$item] == '@' && isset($keys[$index + 1])) {
$output[] = $rule[$keys[$index + 1]];
return;
}
if(isset($keys[$index - 1]) && $rule[$keys[$index - 1]] == '@') {
$output[] = '@';
return;
}
$output[] = $rule[$item];
return;
},
$keys);
echo implode($output);
Instead of giving one input value,I want to give input as array with many value i.e $keys = ['cat1hen','cathen','hencat']
which should give output as ['doga@nt','dogant','antdog']
.How to modify code to do so??
Upvotes: 2
Views: 57
Reputation: 54831
As another solution without regexps, you can wrap your array_walk
into a function and map it to each element of array:
function myFunction($sourceString)
{
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$keys = str_split($sourceString);
$output = [];
array_walk($keys,
function ($item, $index) use ($rule, $keys, &$output) {
if ($rule[$item] == '@' && isset($keys[$index + 1])) {
$output[] = $rule[$keys[$index + 1]];
return;
}
if (isset($keys[$index - 1]) && $rule[$keys[$index - 1]] == '@') {
$output[] = '@';
return;
}
$output[] = $rule[$item];
return;
},
$keys);
return implode($output);
}
print_r(array_map('myFunction', ['cat1hen','cathen','hencat']));
Sample fiddle.
Upvotes: 0
Reputation: 23958
I just slightly modified my code I answered your previous question with.
Added a foreach to loop the words.
$rule =
[
"c" => "d",
"a" => "o",
"t" => "g",
"h" => "a",
"1" => "@",
"e" => "n",
"n" => "t"
];
$orders = ['cat1hen','cathen','hencat'];
foreach($orders as $order){
$arr = str_split($order);
$str ="";
foreach($arr as $key){
$str .= $rule[$key];
}
$str = preg_replace("/(.*?)(@)(.)(.*)/", "$1$3$2$4", $str);
echo $str . "\n";
}
//doga@nt
//dogant
//antdog
Upvotes: 2