【发布时间】:2017-04-13 23:39:12
【问题描述】:
最好使用什么:str_replace、没有 str_replace 或任何其他选项?
例如,我有一个非空数组,它是由 php 基于 XML 文件生成的,我有一个需要更改的变量。如果值在数组中并且变量具有标准值,则应将值更改为其他值(翻译、其他词等)。
我可以用下面的代码做到这一点:
<?php
$ethnic_later = 'niet opgegeven';
$ethnic_array = array( 'Blank',
'getint',
'Aziatisch',
'Zuid-Amerikaans'
);
if (in_array('Blank', $ethnic_array) && $ethnic == 'Blank'){
$ethnic = str_replace($ethnic, 'blanke', $ethnic);
}elseif (in_array('getint', $ethnic_array) && $ethnic == 'getint'){
$ethnic = str_replace($ethnic, 'getinte', $ethnic);
}elseif (in_array('Aziatisch', $ethnic_array) && $ethnic == 'Aziatisch'){
$ethnic = str_replace($ethnic, 'Aziatische', $ethnic);
}elseif(in_array($ethnic, $ethnic_array) && $ethnic == 'Zuid-Amerikaans'){
$ethnic = str_replace($ethnic, 'Zuid Amerikaanse', $ethnic);
}else{
$ethnic = str_replace($ethnic, $ethnic_later, $ethnic);
}
echo 'een mooie ' . $ethnic . ' kleur';
?>
或者我可以直接覆盖$ethnic 的值而不使用php 函数str_replace(),如下所示:
<?php
$ethnic_later = 'niet opgegeven';
$ethnic_array = array( 'Blank',
'getint',
'Aziatisch',
'Zuid-Amerikaans'
);
if (in_array('Blank', $ethnic_array) && $ethnic == 'Blank'){
$ethnic = 'blanke';
}elseif (in_array('getint', $ethnic_array) && $ethnic == 'getint'){
$ethnic = 'getinte';
}elseif (in_array('Aziatisch', $ethnic_array) && $ethnic == 'Aziatisch'){
$ethnic = 'Aziatische';
}elseif(in_array($ethnic, $ethnic_array) && $ethnic == 'Zuid-Amerikaans'){
$ethnic = 'Zuid Amerikaanse';
}else{
$ethnic = $ethnic_later;
}
echo 'een mooie ' . $ethnic . ' kleur';
?>
有更多的可能性可以让这样的事情发挥作用,我在上面发布了 2 个...我相信不使用 str_replace() 的最后一个选项比使用 str_replace() 更快...
我的问题:使用
PHP做我想做的事的最佳方法是什么?你如何做这类任务?
【问题讨论】:
-
'White', 'Black', 'Yellow'ftfy -
@user2176127 是的,这是创建数组的另一种方式,它不是更易读但
array('White', 'Black', 'Yellow');更快?
标签: php arrays variables str-replace