用PHP替换带标记链接的单词

Amo*_*ous 6 php regex tags cakephp

我有一个text($text)和一个单词数组($tags).文本中的这些单词应该替换为指向其他页面的链接,这样它们就不会破坏文本中的现有链接.在CakePHP中,TextHelper中有一个方法可以执行此操作,但它已损坏,并且会破坏文本中现有的HTML链接.该方法假设像这样工作:

$text=Text->highlight($text,$tags,'<a href="/tags/\1">\1</a>',1);
Run Code Online (Sandbox Code Playgroud)

下面是CakePHP TextHelper中的现有代码:

function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>', $considerHtml = false) {
  if (empty($phrase)) {
    return $text;
  }

  if (is_array($phrase)) {
    $replace = array();
    $with = array();

    foreach ($phrase as $key => $value) {
      $key = $value;
      $value = $highlighter;
      $key = '(' . $key . ')';
      if ($considerHtml) {
        $key = '(?![^<]+>)' . $key . '(?![^<]+>)';
      }
      $replace[] = '|' . $key . '|ix';
      $with[] = empty($value) ? $highlighter : $value;
    }
    return preg_replace($replace, $with, $text);
  } else {
    $phrase = '(' . $phrase . ')';
    if ($considerHtml) {
      $phrase = '(?![^<]+>)' . $phrase . '(?![^<]+>)';
    }

    return preg_replace('|'.$phrase.'|i', $highlighter, $text);
  }
}
Run Code Online (Sandbox Code Playgroud)

Chu*_*ess 0

这段代码工作得很好。您可能需要做的是检查 CSS<span class="highlight">并确保将其设置为某种颜色,以便您区分它是高亮的。

.highlight { background-color: #FFE900; }
Run Code Online (Sandbox Code Playgroud)