deansatch Posted February 20, 2009 Share Posted February 20, 2009 I want to bold a search term in my search results. To make it not case sensitive I used str_ireplace(). str_ireplace($_POST['search'], '<strong>'.$_POST['search'].'</strong>',$article); This works but of course it replaces the words lose their original case. e.g. $_POST['search'] = 'hello' $article = 'Hello world!' The article will end up looking like "hello world!" instead of "Hello world!" Is there a better way to insert some strong tags either side of the non-case sensitive word without replacing it? EDIT: Also, I have noticed that this won't work when the article is: 'Once upon a time there was a dog.' And $_POST[search'] = 'time dog' There must be a better way of doing this. Quote Link to comment https://forums.phpfreaks.com/topic/146127-str_ireplace/ Share on other sites More sharing options...
premiso Posted February 20, 2009 Share Posted February 20, 2009 preg_replace is much better suited for this. Just remember if any word containts the keywords, "onetime" "time" will still be bolded, if you do not like this or not want it that way let me know and I will show you the code to avoid this. <?php $_POST['search'] = "time dog"; $string = "Once upon a time there was a dog."; $words = explode(" ", $_POST['search']); foreach ($words as $word) { $string = preg_replace("~" . $word . "~i", "<strong>$0</strong>", $string); } echo $string; die(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/146127-str_ireplace/#findComment-767135 Share on other sites More sharing options...
deansatch Posted February 20, 2009 Author Share Posted February 20, 2009 Thanks a lot. That works. I understand the code apart from the $0 part. Could you explain that bit please? I hate not knowing why something works. Quote Link to comment https://forums.phpfreaks.com/topic/146127-str_ireplace/#findComment-767142 Share on other sites More sharing options...
premiso Posted February 20, 2009 Share Posted February 20, 2009 Thanks a lot. That works. I understand the code apart from the $0 part. Could you explain that bit please? I hate not knowing why something works. $0 just means use the first matched result, in this case $word, in your replacement. This should preserve the word's case as it is basically the raw form/original word as seen in the text. Hope that helps. Quote Link to comment https://forums.phpfreaks.com/topic/146127-str_ireplace/#findComment-767151 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.