Web Dev Guy
Web Dev Guy

Reputation: 1789

Highlight part of a search result in PHP

Ok so I have a bit of PHP code which outputs results pulled from the Wordpress database.

if ($searchPostResults) :
    echo '<ul>';
    foreach ($searchPostResults as $pagePosts)
        echo '<li><span class="searchResult"><a href="' . get_the_permalink($pagePosts->ID) . '" title="">' . get_the_title($pagePosts->ID) . '</a></span></li>';
    echo '</ul>';
else :
    ?>
        <p>No Results</p>
    <?php
endif;

So in each result the keyword will appear. I would like to make that keyword bold.

The keyword is stored here:

$searchVal = (isset($_POST["searchVal"])) ? $_POST["searchVal"] : "";

Example: I'm a search result.

What would be the best way about doing this for each result. I thought about using grep and substrings but this seems a bit long winded.

Cheers

Upvotes: 0

Views: 191

Answers (2)

Divakar Gujjala
Divakar Gujjala

Reputation: 803

With preg_replace method we can highlight the search text.

Below is the sample PHP snippet:

<?php 
    $result = "I'm a search result."; 
    $searchVal = "search";
    $sk = explode(" ",$searchVal); 
    $result = preg_replace('/('.implode('|', $sk) .')/iu', '<strong class="highlighter">\0</strong>', $result);

    echo $result;
?>

Use below pattern to match only words:

$result = preg_replace('/\b('.implode('|', $sk) .')\b/iu', '<strong class="highlighter">\0</strong>', $result);

While Integrating this on your WP code assign title to $result

$result = get_the_title($pagePosts->ID);

In addition to this you can use css to apply styles to the highlighted text.

strong.highlighter { 
    background-color:yellow;
    color:blue;
}

Upvotes: 1

Alister Cameron
Alister Cameron

Reputation: 86

Simply use str_replace:

str_replace($searchVal, '<strong>'.$searchVal.'</strong>', get_the_title($pagePosts->ID))

to replace get_the_title($pagePosts->ID)).

If it doesn't match, the title will pass thru unchanged.

(Note: this will not deal with case mismatches as is.)a

Upvotes: 0

Related Questions