Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/146127-str_ireplace/
Share on other sites

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();
?>

Link to comment
https://forums.phpfreaks.com/topic/146127-str_ireplace/#findComment-767135
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/146127-str_ireplace/#findComment-767151
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.