From 9a4d314b814145e023c9cd782b8959679dcac111 Mon Sep 17 00:00:00 2001 From: phpnut Date: Thu, 4 Oct 2007 02:17:40 +0000 Subject: [PATCH] Closes #707, added Inflector::slug() to return a string with all spaces converted to $replacement and non word characters removed. git-svn-id: https://svn.cakephp.org/repo/branches/1.2.x.x@5712 3807eeeb-6ff5-0310-8944-8be069107fe0 --- cake/libs/inflector.php | 14 +++++++++++++- cake/tests/cases/libs/inflector.test.php | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) 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); }