Ho un testo ($text
) e una serie di parole ($tags
). Queste parole nel testo dovrebbero essere sostituite con collegamenti ad altre pagine in modo che non interrompano i collegamenti esistenti nel testo. In CakePHP c'è un metodo in TextHelper per farlo, ma è corrotto e rompe i collegamenti HTML esistenti nel testo. Il metodo si supponga di lavorare in questo modo:Sostituzione di parole con collegamenti di tag in PHP
$text=Text->highlight($text,$tags,'<a href="/tags/\1">\1</a>',1);
Qui di seguito c'è il codice esistente in 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);
}
}
Non sto chiedendo di evidenziare. Si prega di leggere la domanda. – Amorphous
Fornirai un esempio di '$ text' da esaminare? Il codice funziona bene quando lo provo. Direi che potrebbe essere che i '$ tag' che stai cercando di sostituire possano esistere all'interno di un tag'