Search code examples
phpregexhighlighting

Need to highlight overlapping text using PHP


I am looking for means to highlight certain text on a page. I use <span class="highlight">This is a sample</span> to replace the text "This is a sample" that is found, with the help of the preg_replace function.

My problem arises when there is overlapping text. If I search for the phrase "sample text" on the same page, it is not highlighted. I need the highlighting to merge.

Any help with this problem would be appreciated.

Thanks!


Solution

  • Don't replace text. Find positions of texts that need highlighting, sort them by beginnings and check if in that ordered list item's begining of next item "overlaps" ending of previous.

    Text:
    This is a sample text.
    0123456789...
    Items to highlight: This is and is a.

    Ordered list I'm talking about: [[0, 7], [5, 9]]. 5 and 7 "ovrelap".