So I'm making a search function for comments. Someone else here helped me with the SQL query. What I also want to do is to highlight the search query text in the results.
The results are stored as HTML inside a $variable
.
How can I wrap the search query text inside a <span>
tag for example, without messing up the html.
for eg. the search query can be foo bar
and the output can look like:
<p>bla bla foo bar bla</p>
so it should be something like:
<p>bla <span class="highlight">foo bar</span> bla bla</p>
Simple find and replace:
$resultHTML = str_replace($searchString, '<span class="highlight">'.$searchString.'</span>', $resultHTML );
<?php
$result = "<p>Bla bla foo bar bla bla test x x x</p>";
$query = "foo bar";
// The important point here is, USE single quote ( ' ) in replacement part!!
echo preg_replace( "/($query)/", '<span class="highlight">${1}</span>', $result );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With