From 5d7e9a8d3667933426672b840e97d1c061e1e092 Mon Sep 17 00:00:00 2001 From: Bilge Date: Fri, 14 Feb 2014 01:26:55 +0000 Subject: [PATCH] Optimized replace() and collapseWhitespace() by reusing regexReplace(). Fixed bug in replace() where replacement string was being escaped with preg_quote() and added matching tests. --- src/Stringy.php | 20 ++------------------ tests/CommonTest.php | 3 +++ 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/src/Stringy.php b/src/Stringy.php index 97c6a6d..cc962c9 100644 --- a/src/Stringy.php +++ b/src/Stringy.php @@ -383,13 +383,7 @@ class Stringy implements \Countable, \IteratorAggregate, \ArrayAccess */ public function collapseWhitespace() { - $regexEncoding = mb_regex_encoding(); - mb_regex_encoding($this->encoding); - - $str = mb_ereg_replace('[[:space:]]+', ' ', $this->str); - mb_regex_encoding($regexEncoding); - - return self::create($str, $this->encoding)->trim(); + return $this->regexReplace('[[:space:]]+', ' ')->trim(); } /** @@ -1267,17 +1261,7 @@ class Stringy implements \Countable, \IteratorAggregate, \ArrayAccess */ public function replace($search, $replacement) { - $regexEncoding = mb_regex_encoding(); - mb_regex_encoding($this->encoding); - - // Don't want the args being parsed as regex - $search = preg_quote($search); - $replacement = preg_quote($replacement); - - $str = mb_ereg_replace($search, $replacement, $this->str); - mb_regex_encoding($regexEncoding); - - return self::create($str, $this->encoding); + return $this->regexReplace(preg_quote($search), $replacement); } /** diff --git a/tests/CommonTest.php b/tests/CommonTest.php index b4285db..21399ea 100644 --- a/tests/CommonTest.php +++ b/tests/CommonTest.php @@ -835,6 +835,8 @@ abstract class CommonTest extends PHPUnit_Framework_TestCase array('foo', '', '', 'foo'), array('foo', '\s', '\s', 'foo'), array('foo bar', 'foo bar', '', ''), + array('foo bar', 'foo bar', 'f(o)o', '\1'), + array('\1 bar', 'foo bar', 'foo', '\1'), array('bar', 'foo bar', 'foo ', ''), array('far bar', 'foo bar', 'foo', 'far'), array('bar bar', 'foo bar foo bar', 'foo ', ''), @@ -853,6 +855,7 @@ abstract class CommonTest extends PHPUnit_Framework_TestCase return array( array('', '', '', ''), array('bar', 'foo', 'f[o]+', 'bar'), + array('o bar', 'foo bar', 'f(o)o', '\1'), array('bar', 'foo bar', 'f[O]+\s', '', 'i'), array('foo', 'bar', '[[:alpha:]]{3}', 'foo'), array('', '', '', '', 'msr', 'UTF-8'),