不确定这是否是正确的方法,但这是我现在唯一的方法,所以欢迎新的建议!我正在尝试检测字符串所说的内容,并在此基础上,将其替换为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
把它显示在一个表中。然而,问题是,很明显,当检测到一个字符串时,它们都会被替换,因为每个记录都会被同一个字符串替换。我该如何克服/重新编码/重新评估这一点以使其发挥作用?
根据str_replace
混合str_replace(混合$search,混合$replace,混合$subject[,int&$count])
前2个参数可以是数组,所以您可以像这样使用它:
$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);
}