Skip to content

Commit deed69e

Browse files
committed
Adding ability to input an array parameter for 3rd argument of TextHelper::highlight(). Implements #17.
1 parent 2893b29 commit deed69e

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

cake/libs/view/helpers/text.php

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,28 +64,30 @@ function highlight($text, $phrase, $highlighter = '<span class="highlight">\1</s
6464
}
6565

6666
if (is_array($phrase)) {
67+
6768
$replace = array();
6869
$with = array();
6970

70-
foreach ($phrase as $key => $value) {
71-
$key = $value;
72-
$value = $highlighter;
73-
$key = '(' . $key . ')';
71+
foreach ($phrase as $key => $segment) {
72+
$segment = "($segment)";
73+
7474
if ($considerHtml) {
75-
$key = '(?![^<]+>)' . $key . '(?![^<]+>)';
75+
$segment = "(?![^<]+>)$segment(?![^<]+>)";
7676
}
77-
$replace[] = '|' . $key . '|iu';
78-
$with[] = empty($value) ? $highlighter : $value;
77+
78+
$with[] = (is_array($highlighter)) ? $highlighter[$key] : $highlighter;
79+
$replace[] = "|$segment|iu";
7980
}
8081

8182
return preg_replace($replace, $with, $text);
83+
8284
} else {
83-
$phrase = '(' . $phrase . ')';
85+
$phrase = "($phrase)";
8486
if ($considerHtml) {
85-
$phrase = '(?![^<]+>)' . $phrase . '(?![^<]+>)';
87+
$phrase = "(?![^<]+>)$phrase(?![^<]+>)";
8688
}
8789

88-
return preg_replace('|'.$phrase.'|iu', $highlighter, $text);
90+
return preg_replace("|$phrase|iu", $highlighter, $text);
8991
}
9092
}
9193

cake/tests/cases/libs/view/helpers/text.test.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,21 @@ function testHighlightConsiderHtml() {
164164
$this->assertEqual($this->Text->highlight($text4, array('strong', 'what'), '<b>\1</b>', true), $expected);
165165
}
166166

167+
/**
168+
* testHighlightMulti method
169+
*
170+
* @access public
171+
* @return void
172+
*/
173+
function testHighlightMulti() {
174+
$text = 'This is a test text';
175+
$phrases = array('This', 'text');
176+
$result = $this->Text->highlight($text, $phrases, array('<b>\1</b>', '<em>\1</em>'));
177+
$expected = '<b>This</b> is a test <em>text</em>';
178+
$this->assertEqual($expected, $result);
179+
180+
}
181+
167182
/**
168183
* testStripLinks method
169184
*

0 commit comments

Comments
 (0)