1
0
mirror of https://github.com/danielstjules/Stringy.git synced 2025-08-10 23:34:00 +02:00

Optimized replace() and collapseWhitespace() by reusing regexReplace().

Fixed bug in replace() where replacement string was being escaped with preg_quote() and added matching tests.
This commit is contained in:
Bilge
2014-02-14 01:26:55 +00:00
parent 9399f7a694
commit 5d7e9a8d36
2 changed files with 5 additions and 18 deletions

View File

@@ -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);
}
/**

View File

@@ -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'),