1
0
mirror of https://github.com/danielstjules/Stringy.git synced 2025-08-09 14:56:31 +02:00

Merge pull request #21 from Bilge/dry-regex-replace

Optimized replace() and collapseWhitespace() by reusing regexReplace().
This commit is contained in:
Daniel St. Jules
2014-02-14 07:09:57 -05:00
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'),