foreach循环中的条件str_replace

时间:2015-12-04 11:35:03

标签: php if-statement foreach

不确定这是否是正确的方法,但这是我现在唯一的一个,所以欢迎新的建议!我正在尝试检测字符串所说的内容,并在此基础上将其替换为foreach内的自定义信息。

foreach($customfields as $field)
{
    if($field->title == 'Date of Birth')
    {
        $title = str_replace($field->title, 'Date of Birth', 'Data urodzenia');
    }
    else if($field->title == 'Address Line 1')
    {
        // str_replace doesn't work, as the above has already been done, replacing each $field->title.
    }
    // rest of code
}

然后我使用$title将其显示在表格中。 然而,问题是,当检测到一个字符串时,它们全部被替换,因为每个记录都被相同的字符串替换。我怎样才能克服/重新编码/重新认证它以使其有效?

1 个答案:

答案 0 :(得分:2)

根据str_replace

  

混合str_replace(混合$ search,混合$ replace,混合$ subject [,int& $ count])

前两个参数可以是数组,因此您可以使用它:

$searches = array('Date of Birth', 'Address Line 1');
$replacements = array('Data urodzenia', 'Another address replacement');

$customFields = array_map(function($field) use ($searches, $replacements) {
    $field->title = str_replace($searches, $replacements, $field->title);
    return $field;
}, $customFields);

另外,你给参数的顺序是错误的,在调用函数时要替换为第三个的字符串。

对于低于5.3的PHP版本,不支持闭包,因此您可以在foreach循环中执行替换:

$searches = array('Date of Birth', 'Address Line 1');
$replacements = array('Data urodzenia', 'Another address replacement');

foreach($customfields as $field) {
    $field->title = str_replace($searches, $replacements, $field->title);
}
相关问题