Reputation: 470
Not sure if this is the correct approach, but this is the only one that is coming to me right now, so new suggestions are welcome! I am trying to detect what a string says, and based on that, replace it with custom information inside a 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
}
And then I display it in a table using $title
.
However, the issue is that obviously when one string is detected, they are all replaced, as each record gets replaced with the same string. How can I overcome/recode/reapproach this to make it work?
Upvotes: 0
Views: 895
Reputation: 24276
According to str_replace
mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
The first 2 arguments could be arrays, so you can use it like:
$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);
Also, the order you gave to the arguments is wrong, the string to do replacements into being the third one when calling the function.
For PHP versions lower than 5.3 the closures are not supported, so you can do the replacements inside the foreach loop as:
$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);
}
Upvotes: 2