diff --git a/src/Slugify.php b/src/Slugify.php index 7d1e22e0..c63246c3 100644 --- a/src/Slugify.php +++ b/src/Slugify.php @@ -23,6 +23,8 @@ */ class Slugify implements SlugifyInterface { + const LOWERCASE_NUMBERS_DASHES = '/([^a-z0-9]|-)+/'; + /** @var array */ protected $rules = array( // Numeric characters @@ -459,6 +461,18 @@ class Slugify implements SlugifyInterface ) ); + /** @var string */ + protected $regExp; + + /** + * + * @param string $regExp + */ + public function __construct($regExp = self::LOWERCASE_NUMBERS_DASHES) + { + $this->regExp = $regExp; + } + /** * Returns the slug-version of the string. * @@ -470,7 +484,7 @@ class Slugify implements SlugifyInterface public function slugify($string, $separator = '-') { $string = strtolower(strtr($string, $this->rules)); - $string = preg_replace('/([^a-z0-9]|-)+/', $separator, $string); + $string = preg_replace($this->regExp, $separator, $string); $string = strtolower($string); return trim($string, $separator); @@ -546,13 +560,27 @@ public function getRulesets() return $this->rulesets; } + /** + * Sets the regular expression used to sanitize the slug + * + * @param string $regExp + */ + public function setRegExp($regExp) + { + $this->regExp = $regExp; + + return $this; + } + /** * Static method to create new instance of {@see Slugify}. * + * @param string $regExp The regular expression to be applied to strings when calling slugify + * * @return Slugify */ - public static function create() + public static function create($regExp = self::LOWERCASE_NUMBERS_DASHES) { - return new static(); + return new static($regExp); } } diff --git a/tests/SlugifyTest.php b/tests/SlugifyTest.php index 6659c85b..31933f89 100644 --- a/tests/SlugifyTest.php +++ b/tests/SlugifyTest.php @@ -110,6 +110,33 @@ public function createReturnsAnInstance() $this->assertInstanceOf('Cocur\\Slugify\\SlugifyInterface', Slugify::create()); } + /** + * @test + * @covers Cocur\Slugify\Slugify::setRegExp() + */ + public function otherRegExpsProduceOtherResults() + { + $actual = 'File Name.tar.gz'; + $expected = 'file-name.tar.gz'; + + $this->assertNotEquals($expected, $this->slugify->slugify($actual)); + $this->slugify->setRegExp('/([^a-z0-9.]|-)+/'); + $this->assertEquals($expected, $this->slugify->slugify($actual)); + } + + /** + * @test + * @covers Cocur\Slugify\Slugify::__construct() + */ + public function constructWithOtherRegexp() + { + $actual = 'File Name.tar.gz'; + $expected = 'file-name.tar.gz'; + + $this->slugify = new Slugify('/([^a-z0-9.]|-)+/'); + $this->assertEquals($expected, $this->slugify->slugify($actual)); + } + public function provider() { return array(