简体   繁体   中英

PHP str_ireplace is not replacing the value in array

I have the below function and don't know what I'm missing to make it work:

private function highlight_words($items, $word) {      
    return str_ireplace($word, '<span class="highlight">'.$word.'</span>', $items);         
}

Where $items is an array and definitely contains the string $word and $word is not empty.

First I'm calling search function like this -> $this->set('results', $this->search()); and from the search function -> return $this->highlight_words($results, $search_term);

As of php.net it should work as it's now:

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

I was trying to replace string in multidimensional array where str_ireplace wasn't taking any effect. Had to re-write my function a little bit to make it work:

private function highlight_words($items, $word) {      
    foreach ($items as $key => $item) {
        foreach ($item as $k => $i) {           
            $items[$key][$k] = str_ireplace($word, '<span class="highlight">'.$word.'</span>', $i);                
        }
    }
    return $items;          
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM