0

Hi everyone so my problem is 90% like this one: How to make search results "clickable"

(please read it). But the only difference is that in the best solution, the str_replace is case sensitive, i tried to replace it with str_ireplace, but the problem was that the word becomes bold but lowercase in the same time. Thanks for help!

code:

if(isset($_POST['tosearchfor']))
        {
            $query = $db->query('SELECT * FROM searchfor WHERE title LIKE \'%'.$_POST['tosearchfor'].'%\'');

                    for($i=0; $i<20;  $i++)
                    {
                        if($result = $query->fetch())
                        {
                            $result = str_ireplace($_POST['tosearchfor'], '<b>'.$_POST['tosearchfor'].'</b>', $result);
                            echo '<div class="result">
                            <a class="title" href="#">'.$result['title'].'</a>
                            <span class="link">
                                <span style="font-size:15px;position:relative;top:0.8px;padding-right:2px;">&#8227;</span>
                                https://www.qsoft.com/'.$result['link'].'
                            </span>
                            <span class="details">'.$result['details'].'</span>
                            </div>';
                        }
                        else
                        {
                            if($i==0)
                            {
                                echo 'Sorry, no resluts found for : <strong>'.$_POST['tosearchfor'].'</strong>';
                            }
                        }
                    }   
        }
QApps
  • 303
  • 1
  • 8

1 Answers1

1

Your problem lies in this line:

$result = str_ireplace($_POST['tosearchfor'], '<b>'.$_POST['tosearchfor'].'</b>', $result);

You're case-insensitively replacing all instances of $_POST['tosearchfor'] (for example: "apple") with '<b>'.$_POST['tosearchfor'].'</b>'. This is going to change apple to <b>apple</b>, Apple to <b>apple</b> and snapple to sn<b>apple</b>.

What you want instead is to case-insensitively replace apple with whatever matches surrounded by <b>...</b>, and preg_replace provides you with that option.

$result = preg_replace("/\b(" . $_POST['tosearchfor'] . ")\b/i", "<b>$1</b>", $result);

This pattern also includes the word boundary character (\b), so it won't match snapple or apples, but it will match apple, Apple, and APPLE because of the case-insensitive flag (/i). It then replaces all matches with $1, which is code for whatever matched in the first set of parentheses, surrounded by <b> and </b>.

See the difference here: https://ideone.com/PrdQOS

Hatchet
  • 5,320
  • 1
  • 30
  • 42