PHP - select text from a string containing HTML

So, I am doing a search function for comments. Someone here helped me with a SQL query . I also want to highlight the query text in the search results.

Results are saved as HTML inside $variable. How can I wrap the text of a search query inside a tag <span>, for example, without html corruption.

eg. A search query may be foo bar, and the result may look like this:

<p>bla bla foo bar bla</p>

so it should be something like:

<p>bla <span class="highlight">foo bar</span> bla bla</p>
+5
source share
7 answers

I think this is harder than it sounds. If we are looking foo bar, then

<p>bla bla foo bar bla</p>

will be converted to

<p>bla <span class="highlight">foo bar</span> bla bla</p>

? , foo bar HTML:

<p>bla bla <span class="foo bar">foo bar</span> bla</p>

<p>bla <span class="<span class="highlight">foo bar</span>">foo bar</span> bla bla</p>

? , CakePHP (, , ) highlight(), HTML-. , , , .

+2

:

$resultHTML = str_replace($searchString, '<span class="highlight">'.$searchString.'</span>', $resultHTML );
+7
<?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 );
+2
$searchString = 'foo bar';
$searchResult = '<p>bla bla foo bar bla</p>';

var_dump(str_replace($searchString, '<span>'.$searchString.'</span>', $searchResult));

var_dump(preg_replace('/'.$searchString.'/', '<span>'.$searchString.'</span>', $searchResult));
+1

, HTML, "<span>" str_replace().

, , HTML .

If the search term can contain HTML (i.e., highlighting can span the borders of tags), things get a lot more complicated and you won’t get away with a smart shortcut like the one above.

+1
source

I had the same question, but I found this

The code is built to randomly change the highlight color, but this is done using a function, so it’s easy to change it to use a single color:

     $color = '#FCB514'; //self::generate_colors();

First post!

+1
source

text-shadow: 1px 1px 1px # FCD600;

0
source

All Articles