Text helper highlight method now handles HTML tags correctly. Closes #2242

git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@6912 3807eeeb-6ff5-0310-8944-8be069107fe0
This commit is contained in:
joelmoss 2008-05-17 18:45:24 +00:00
parent ec12b91657
commit 64e68c9b7c
2 changed files with 24 additions and 5 deletions

View file

@ -54,10 +54,11 @@ class TextHelper extends AppHelper {
* @param string $text Text to search the phrase in
* @param string $phrase The phrase that will be searched
* @param string $highlighter The piece of html with that the phrase will be highlighted
* @param boolean $considerHtml If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
* @return string The highlighted text
* @access public
*/
function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>') {
function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</span>', $considerHtml = false) {
if (empty($phrase)) {
return $text;
}
@ -69,14 +70,22 @@ class TextHelper extends AppHelper {
foreach ($phrase as $key => $value) {
$key = $value;
$value = $highlighter;
$replace[] = '|(' . $key . ')|i';
$key = '(' . $key . ')';
if ($considerHtml) {
$key = '(?![^<]+>)' . $key . '(?![^<]+>)';
}
$replace[] = '|' . $key . '|i';
$with[] = empty($value) ? $highlighter : $value;
}
return preg_replace($replace, $with, $text);
} else {
return preg_replace("|({$phrase})|i", $highlighter, $text);
$phrase = '(' . $phrase . ')';
if ($considerHtml) {
$phrase = '(?![^<]+>)' . $phrase . '(?![^<]+>)';
}
return preg_replace('|'.$phrase.'|i', $highlighter, $text);
}
}
/**

View file

@ -93,6 +93,16 @@ class TextTest extends UnitTestCase {
$this->assertEqual($result, $text);
}
function testHighlightConsiderHtml() {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>';
$text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>';
$text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEqual($this->Text->highlight($text1, 'strong', '<b>\1</b>', true), '<p><b>strong</b>bow isn&rsquo;t real cider</p>');
$this->assertEqual($this->Text->highlight($text2, 'strong', '<b>\1</b>', true), '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>');
$this->assertEqual($this->Text->highlight($text3, 'strong', '<b>\1</b>', true), $text3);
}
function testStripLinks() {
$text = 'This is a test text';
$expected = 'This is a test text';