1

I want to mark (highlight) the keywords a user has input as search parameters. I've tried the following PHP code to do this. It adds the tag effectively but for some reason displays each string as "Array" rather than it's value.

$find = array("HELLO","WORLD"); // Case-insensitive
$arr = array("Hello","world","!");
print_r(str_ireplace($find,'<mark>'.$find.'</mark>',$arr));

https://i.imgur.com/7vryXlY (demo image, not enough rep to embed)

2
  • change it to this print_r(str_ireplace($find,$replace,$arr)); then it will work Commented Jun 2, 2021 at 16:11
  • Thanks for your suggestion @ShakeelAhmad! That does work, but I need the html <mark> tag added to the results which that doesn't do. Edit: I realise I'd left the $replace array in my code, which may have caused confusion, removed it now as it's unneeded. Commented Jun 2, 2021 at 16:17

1 Answer 1

1

You can only replace an array with an array. You can either loop:

$result = $arr;
foreach($find as $v) {
    $result = str_ireplace($v, "<mark>$v</mark>", $result);
}

Or create a replacement array from the $find array:

$repl = array_map(function($v) { return "<mark>$v</mark>"; }, $find);
$result = str_ireplace($find, $repl, $arr);

Or combined:

$result = str_ireplace($find, array_map(function($v) { return "<mark>$v</mark>"; }, $find), $arr);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for taking the time to help, that combined solution is very concise and worked a treat!

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.