DolDurma
DolDurma

Reputation: 17303

php replace in array with custom replacement data

In this code as for example:

$hello=['aaaa','bbbb','cccc'];
$by=['1111','2222','3333'];
$data = "1111 aaaa cccc";

I want to replace $by with $hello with this custom replacement data for example:

str_replace( $hello , "<b>". $by . "</b>" , $data);

But I get array to string error. How can I use this custom replace method?

Upvotes: 2

Views: 54

Answers (1)

Kevin
Kevin

Reputation: 41885

You need to feed the arguments as an array in str_replace, by concatenating the string, it yields the error. You apply the bold text concatenation on the array replacement strings first, then you use the str_replace.

Here's the idea:

$by = array_map(function($e) {
    return "<b>{$e}</b>";
}, $by);

When you use it:

$hello=['aaaa','bbbb','cccc']; // needles
$by=['1111','2222','3333']; // replacements
$by = array_map(function($e) { // apply bold to replacements
    return "<b>{$e}</b>";
}, $by);
$data = "1111 aaaa cccc"; // haystack
$data = str_replace( $hello , $by, $data); // actual replacements
                //     ^ array  ^

Upvotes: 2

Related Questions