Highlight text, except html tags

前端 未结 3 520
抹茶落季
抹茶落季 2021-01-18 06:26

I\'m using the code below to highlight some keywords in a text:

$message = str_ireplace($words,\'\'.$words.\'         


        
3条回答
  •  遥遥无期
    2021-01-18 07:20

    From http://forum.phpfrance.com/vos-contributions/remplacement-selectif-hors-dans-balises-html-t199.html

    function mon_rplc_callback($capture){
      global $arg;
      return ($arg['flag'] == 1)
      ? $arg['fct']($arg['from'], $arg['to'], $capture[1]).$capture[2]
      : $capture[1].$arg['fct']($arg['from'], $arg['to'], $capture[2]);
    }
    
    function split_tag($from, $to, $txt, $fct, $flag = 1){
      global $arg;
      $arg = compact('from', 'to', 'fct', 'flag');
      return preg_replace_callback('#((?:(?!<[/a-z]).)*)([^>]*>|$)#si', "mon_rplc_callback", $txt);
    }
    

    When $flag == 1, the replacement function is applied outside HTML. When $flag == -1, the replacement function is applied inside HTML.

    Applied to your example, it would give something like this:

    echo split_tag($words, ''.$words.'', $message, 'str_ireplace', 1);
    

    Enjoy! ;)

提交回复
热议问题