Search code examples
phphtmlstrpos

search string with html tags


I have html content in PHP variable and I want to search for particular string with it's tags.

suppose my variable is

$var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>

Now I want to search for how in $var then it should return me with it's tag so I should get how

how this can be done using PHP?

Any help would be appreciated.


Solution

  • Using regex:

    $search = 'how';
    $var = "<html>Hi.. <strong>how</strong>are <u>you?</u></html>";
    preg_match_all('/<[^>]+>'.$search.'<\/[^>]+>/',$var,$matches);
    $found = $matches[0][0];
    echo $found;
    

    Output:

    how

    To get all how strings, those with and without tags, change your regex to this (add OR | operator:

    preg_match_all('/<[^>]+>'.$search.'<\/[^>]+>|\b'.$search.'\b/',$var,$matches);