У меня есть текст ( $ text
) и массив слов ( $ tags
). Эти слова в тексте должны быть заменены ссылками на другие страницы, чтобы они не нарушали существующие ссылки в тексте. В CakePHP есть метод в TextHelper для этого, но он поврежден и разрушает существующие HTML-ссылки в тексте. Предполагается, что метод работает следующим образом:
$text=Text->highlight($text,$tags,'<a href="/tags/\1">\1</a>',1);
Ниже приведен существующий код в 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);
}
}