Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - highlight text from a string containing HTML

Tags:

html

string

php

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>
like image 941
Alex Avatar asked Dec 14 '10 20:12

Alex


2 Answers

Simple find and replace:

$resultHTML = str_replace($searchString, '<span class="highlight">'.$searchString.'</span>', $resultHTML );
like image 146
jd. Avatar answered Oct 31 '22 03:10

jd.


<?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 );
like image 40
Bnymn Avatar answered Oct 31 '22 01:10

Bnymn