Browse Source

Merge pull request #10375 from cakephp/text-highlight-limit

Allow to set the limit number of replacements when highlighting text
Mark Story 9 years ago
parent
commit
1cd271c451
2 changed files with 25 additions and 5 deletions
  1. 6 4
      src/Utility/Text.php
  2. 19 1
      tests/TestCase/Utility/TextTest.php

+ 6 - 4
src/Utility/Text.php

@@ -456,7 +456,8 @@ class Text
      *
      * - `format` The piece of HTML with that the phrase will be highlighted
      * - `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
-     * - `regex` a custom regex rule that is used to match words, default is '|$tag|iu'
+     * - `regex` A custom regex rule that is used to match words, default is '|$tag|iu'
+     * - `limit` A limit, optional, defaults to -1 (none)
      *
      * @param string $text Text to search the phrase in.
      * @param string|array $phrase The phrase or phrases that will be searched.
@@ -473,7 +474,8 @@ class Text
         $defaults = [
             'format' => '<span class="highlight">\1</span>',
             'html' => false,
-            'regex' => "|%s|iu"
+            'regex' => '|%s|iu',
+            'limit' => -1,
         ];
         $options += $defaults;
         extract($options);
@@ -492,7 +494,7 @@ class Text
                 $replace[] = sprintf($options['regex'], $segment);
             }
 
-            return preg_replace($replace, $with, $text);
+            return preg_replace($replace, $with, $text, $limit);
         }
 
         $phrase = '(' . preg_quote($phrase, '|') . ')';
@@ -500,7 +502,7 @@ class Text
             $phrase = "(?![^<]+>)$phrase(?![^<]+>)";
         }
 
-        return preg_replace(sprintf($options['regex'], $phrase), $format, $text);
+        return preg_replace(sprintf($options['regex'], $phrase), $format, $text, $limit);
     }
 
     /**

+ 19 - 1
tests/TestCase/Utility/TextTest.php

@@ -711,7 +711,7 @@ HTML;
     }
 
     /**
-     * testHighlight method
+     * Tests highlight() method.
      *
      * @return void
      */
@@ -746,6 +746,24 @@ HTML;
     }
 
     /**
+     * Tests highlight() method with limit.
+     *
+     * @return void
+     */
+    public function testHighlightLimit()
+    {
+        $text = 'This is a test text with some more text';
+        $phrases = ['This', 'text'];
+        $result = $this->Text->highlight($text, $phrases, ['format' => '<b>\1</b>']);
+        $expected = '<b>This</b> is a test <b>text</b> with some more <b>text</b>';
+        $this->assertEquals($expected, $result);
+
+        $result = $this->Text->highlight($text, $phrases, ['format' => '<b>\1</b>', 'limit' => 1]);
+        $expected = '<b>This</b> is a test <b>text</b> with some more text';
+        $this->assertEquals($expected, $result);
+    }
+
+    /**
      * testHighlightHtml method
      *
      * @return void