2

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?

1 Answer 1

2

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  ^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.