php replace non matches from two arrays
How do you replace all non matches from one array that are not defined within the other array, i have kind of got working but its not exactly right. as i will show you.
the result is, but wrong.
- - £ 8 - - - - - - - -
The required result should be
£ 8 - -
this is how my code is
$vals_to_keep = array(8, 'y', '£');
$replace_if_not_found = array('£', 8, '#', 't'); // replace if not in above array
$result = '';
foreach ($replace_if_not_found as $d) {
foreach ($vals_to_keep as $ok) {
if(strcmp($d, $ok) == 0开发者_JAVA百科){
$result .= $d . " ";
}else
$result .= str_replace($d, $ok ,'-') . " ";
}
}
echo $result;
use in_array http://php.net/manual/en/function.in-array.php
foreach ($replace_if_not_found as $d) {
if (in_array($d, $vals_to_keep))
$result .= $d . " ";
else
$result .= str_replace($d, $ok ,'-') . " ";
}
You could loop over all of the items in $replace_if_not_found
replacing them with -
, or not, as appropriate.
Using closure in PHP 5.3 or above
$result = array_map(function($item) use ($vals_to_keep) {
return in_array($item, $vals_to_keep, TRUE) ? $item : '-';
}, $replace_if_not_found);
echo implode(' ', $result);
Using a foreach loop
$result = array();
foreach ($replace_if_not_found as $item) {
if (in_array($item, $vals_to_keep, TRUE)) {
$result[] = $item;
} else {
$result[] = '-';
}
}
echo implode(' ', $result;
精彩评论