diff --git a/cake/libs/inflector.php b/cake/libs/inflector.php index c4bf31625..750fa94d4 100644 --- a/cake/libs/inflector.php +++ b/cake/libs/inflector.php @@ -411,8 +411,20 @@ class Inflector extends Object { $variable = preg_replace('/\\w/', $replace, $string, 1); return $variable; } +/** + * Returns a string with all spaces converted to $replacement and non word characters removed. + * + * @param string $string + * @param string $replacement + * @return string + * @access public + * @static + */ + function slug($string, $replacement = '_') { + $string = preg_replace(array('/[^\w\s]/', '/\\s+/') , array(' ', $replacement), $string); + return $string; + } } - /** * Enclose a string for preg matching. * diff --git a/cake/tests/cases/libs/inflector.test.php b/cake/tests/cases/libs/inflector.test.php index 994e4fd62..c828770ee 100644 --- a/cake/tests/cases/libs/inflector.test.php +++ b/cake/tests/cases/libs/inflector.test.php @@ -173,6 +173,20 @@ class InflectorTest extends UnitTestCase { $this->assertEqual($result, $expected); } + function testInflectorSlug() { + $result = $this->Inflector->slug('Foo Bar: Not just for breakfast any-more'); + $expected = 'Foo_Bar_Not_just_for_breakfast_any_more'; + $this->assertEqual($result, $expected); + + $result = $this->Inflector->slug('Foo Bar: Not just for breakfast any-more', "-"); + $expected = 'Foo-Bar-Not-just-for-breakfast-any-more'; + $this->assertEqual($result, $expected); + + $result = $this->Inflector->slug('Foo Bar: Not just for breakfast any-more', "+"); + $expected = 'Foo+Bar+Not+just+for+breakfast+any+more'; + $this->assertEqual($result, $expected); + } + function tearDown() { unset($this->Inflector); }