php替换两个数组中不匹配的内容
如何替换一个数组中未在另一个数组中定义的所有不匹配项,我已经开始工作,但它并不完全正确。正如我将向您展示的那样。
结果是,但是错误的。
- - £ 8 - - - - - - - -
所需的结果应该是
£ 8 - -
我的代码是这样的
$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){
$result .= $d . " ";
}else
$result .= str_replace($d, $ok ,'-') . " ";
}
}
echo $result;
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){
$result .= $d . " ";
}else
$result .= str_replace($d, $ok ,'-') . " ";
}
}
echo $result;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 in_array http://php.net/manual/en/function.in-array .php
use in_array http://php.net/manual/en/function.in-array.php
您可以循环遍历
$replace_if_not_found
中的所有项目,根据需要将其替换为-
或不替换。在 PHP 5.3 或更高版本中使用闭包
使用 foreach 循环
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
Using a foreach loop