From aa87fe80b3fbe9ed266a1e9ed47bb3dea430d297 Mon Sep 17 00:00:00 2001 From: Frederic Massart Date: Fri, 16 Aug 2013 10:21:01 +0800 Subject: [PATCH] MDL-40877 core_text: Added UTF-8 safe strrchr method --- lib/classes/text.php | 32 +++++++++++++++++++++++++++++++- lib/tests/text_test.php | 11 +++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/lib/classes/text.php b/lib/classes/text.php index 1ca51f8608b..9ce3ea4e8c9 100644 --- a/lib/classes/text.php +++ b/lib/classes/text.php @@ -238,6 +238,36 @@ class core_text { return $result; } + /** + * Finds the last occurrence of a character in a string within another. + * UTF-8 ONLY safe mb_strrchr(). + * + * @param string $haystack The string from which to get the last occurrence of needle. + * @param string $needle The string to find in haystack. + * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle). + * @return string|false False when not found. + * @since 2.4.6, 2.5.2, 2.6 + */ + public static function strrchr($haystack, $needle, $part = false) { + + if (function_exists('mb_strrchr')) { + return mb_strrchr($haystack, $needle, $part, 'UTF-8'); + } + + $pos = self::strrpos($haystack, $needle); + if ($pos === false) { + return false; + } + + $length = null; + if ($part) { + $length = $pos; + $pos = 0; + } + + return self::substr($haystack, $pos, $length, 'utf-8'); + } + /** * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3. * @@ -331,7 +361,7 @@ class core_text { * @return int the numeric position of the last occurrence of needle in haystack */ public static function strrpos($haystack, $needle) { - if (function_exists('mb_strpos')) { + if (function_exists('mb_strrpos')) { return mb_strrpos($haystack, $needle, null, 'UTF-8'); } else { return iconv_strrpos($haystack, $needle, 'UTF-8'); diff --git a/lib/tests/text_test.php b/lib/tests/text_test.php index 1aa16f30c43..fb33750405b 100644 --- a/lib/tests/text_test.php +++ b/lib/tests/text_test.php @@ -360,5 +360,16 @@ class core_text_testcase extends advanced_testcase { $this->assertSame($textlib->specialtoascii('ábc'), 'abc'); $this->assertSame($textlib->strtotitle('abc ABC'), 'Abc Abc'); } + + /** + * Test strrchr. + */ + public function test_strrchr() { + $str = "Žluťoučký koníček"; + $this->assertSame('koníček', core_text::strrchr($str, 'koní')); + $this->assertSame('Žluťoučký ', core_text::strrchr($str, 'koní', true)); + $this->assertFalse(core_text::strrchr($str, 'A')); + $this->assertFalse(core_text::strrchr($str, 'ç', true)); + } }