There is an html page:

<p> какой-то текст найди </p> <p> меня еще какой-то текст </p> 

And there is a phrase

 "найди меня" 

It is required to highlight it on this page. The phrase can intersect with any tags, as in the example.

As an option, you should get something like this:

 <p> какой-то текст <span class="red">найди</span> </p> <p> <span class="red">меня</span> еще какой-то текст </p> 

How to do this using php?

  • PHP is a programming language specifically designed for writing web applications (scripts) that run on a web server. And CSS is a formal language for describing the appearance of a document written using a markup language. Maybe you should think about styles? - Egor
  • I am interested in the algorithm for finding these occurrences and then framing them in the corresponding tags - Vitaly
  • there will be a lot of project JS - Volodymyr
  • Show an example on js - Vitali
  • well, or look in the string (the weight of the document) for the substring that starts on find and ends on me .. and make a check so that between them there is a maximum of n characters .. (maybe there are more words between them) .. well, or check for tags do .. in short regulars to help - Volodymyr

2 answers 2

You can use regular expressions, only one word will be searched for ...

 function search_replace($beginText,$search){ $patterns = "/(".$search.")+/iu"; $replace = "<span style='color:red'><em>$1</em></span>";// На что заменить $endText = PREG_REPLACE($patterns,$replace,$beginText);// Замена return $endText; } echo(searhh_replase("<p> какой-то текст найди </p> <p> меня еще какой-то текст </p>","найди")) 
  • This is not a solution to my problem. Phrase will not find - Vitali
  • If you split a phrase by words and each time in a cycle, you input a string with the search for the previous word to the input of this function, you should get - Boroda95
  • Did not quite understand, can the code? - Vitali

If you never made a mistake, it should work

 $text = 'Длинный текст с тегами'; $match = 'найди меня'; $matchPos = 0; $opentag = false; $positions = []; $curPos = []; $startPos = 0; for ($i = 0; $i < strlen($text); $i++) { switch ($text[$i]) { case '<': if ($matchPos > 0) $curPos[] = [$startPos, $i]; $opentag = true; break; case '>': if ($matchPos > 0) $startPos = $i; $opentag = false; break; default: if (!$opentag) { if ($text[$i] === $match[$matchPos]) { if ($matchPos === 0) $startPos = $i; else if ($matchPos === strlen($match) - 1) { $curPos[] = [$startPos, $i]; $positions[] = $curPos; $curPos = []; $matchPos = 0; } $matchPos++; } else { $curPos = []; $matchPos = 0; } } } } for ($i = count(positions) - 1; $i >= 0; $i--) { for ($j = count(positions[i]) - 1; $j >= 0; $j--} { $text = substr_replace($text, '</span>', $positions[$i][$j][1]); $text = substr_replace($text, '<span class="selected">', $positions[$i][$j][0]); }