<?php
/**
* Re-order the characters from $T using the order of characters in $O.
*
* @param string $T the string to re-order
* @param string $O the string that specifies the desired order
* @return string the re-ordered $T
*/
function reorder($T, $O)
{
// Convert $T and $O to arrays of characters
$t = str_split($T);
$o = str_split($O);
// Compute the index of each character from $T in $O
// Use -1 for characters that do not appear in $O
$m = array_map(function($x) use ($o) {
$p = array_search($x, $o);
return ($p === FALSE) ? -1 : $p;
},
$t
);
// Sort $m and $t simultaneously; $t will follow the changes applied to $m
array_multisort($m, $t);
// Join the sorted characters of $T back and return as string
return implode('', $t);
}
$order = 'eloh';
echo('hello => '.reorder('hello', $order)."\n");
echo('help => '.reorder('help', $order)."\n");
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
hello => elloh
help => pelh