【问题标题】:What is the best to use: str_replace, no str_replace or any other option?最好使用什么:str_replace、没有 str_replace 或任何其他选项?
【发布时间】: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


【解决方案1】:

创建一个数组,该数组由您期望在 $ethnic 中的值进行索引,并包含您希望 $ethnic 变量映射到的字符串,如下所示:

<?php
$ethnic_later = 'niet opgegeven';
$ethnic_array = array(  'Blank' => 'blanke',
                'getint' => 'getinte',
                'Aziatisch' => 'Aziatische',
                'Zuid-Amerikaans' => 'Zuid Amerikaanse'
                );  
if (isset($ethnic_array[$ethnic])) {
        $ethnic = $ethnic_array[$ethnic];
}else{
        $ethnic = $ethnic_later;
}

echo 'een mooie ' . $ethnic . ' kleur';

当您想添加更多 $ethnics 时,请向数组中添加更多元素。

【讨论】:

  • 感谢您的输入,代码更短,可能更快,我没有测试速度,.,
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多