Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rezaulhreza's avatar

Regex to match keywords and highlights only the matched words

I am trying to make a global search bar. with highlighting the keyword it passess all the test except thelast one. if someone search for 86190 it should index through 01908 619060 and match the 8 6190. At present it does highlight the whole word but also highlighting other texts which does not match the search term this test fails. The code is below: Parent Class:

    {
        if ($this->term == '') {
            return $expression;
        }

        // Highlight expression containing spaces when it matches a term without spaces
        if ($this->stringsMatchIgnoringSpaces($this->term, $expression)) {
            return $this->highlight(e($expression));
        }

        // Avoid matching term inside an HTML tag or entity
        // see https://stackoverflow.com/questions/958095/use-regex-to-find-specific-string-not-in-html-tag#answer-63461873


        //matches the phone number but also returns 4 gladstone and other phone number in the highlighted area
        
        return preg_replace('/' . $this->term . '(?![^<&]*?[>;])|(^\d+\s+\w+)/i', $this->highlight('LARACASTS_SNIPPET_PLACEHOLDER'), e($expression));
}


```

This is the test file code
```class HighlighterTest extends TestCase
{
    public function data()
    {
        return [
            // [$term, $expression, $expected]
            ['abc', 'abc dental', '<mark>abc</mark> dental'],
            ['abc', 'ABC dental', '<mark>ABC</mark> dental'],
            ['abc', 'The Abc dental', 'The <mark>Abc</mark> dental'],
            ['', 'ABC dental', 'ABC dental'],
            ['a', 'Smith & Associates', 'Smith &amp; <mark>A</mark>ssoci<mark>a</mark>tes'],
            ['da11 0ef', 'DA11 0EF', '<mark>DA11 0EF</mark>'],
            ['da110ef', 'DA11 0EF', '<mark>DA11 0EF</mark>'],
            ['01474 320076', '01474 320076', '<mark>01474 320076</mark>'],
            ['01474320076', '01474 320076', '<mark>01474 320076</mark>'],
            ['86190', '01908 619060', '<mark>01908 619060</mark>'],
        ];
    }

    /**
     * @test
     * @dataProvider data
     */
    function it_can_highlight_matched_patterns($term, $expression, $expected)
    {
        $hl = new Highlighter($term);

        $this->assertEquals($expected, $hl($expression));
    }

    /** @test */
    function it_doesnt_highlight_unmatched_patterns()
    {
        $hl = new Highlighter('86190'); //this is the text i want to highlight
//fails
        $this->assertEquals('4 Gladstone', $hl('4 Gladstone'));
        $this->assertEquals('01244 831181', $hl('01244 831181'));
    }
}
```
0 likes
0 replies

Please or to participate in this conversation.