diff --git a/README.md b/README.md index 2e03fc4..c16ab6b 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,7 @@ Converts each tab in a string to some number of spaces, as defined by $tabLength. By default, each tab is converted to 4 consecutive spaces. ```php -S:::toSpaces(' String speech = "Hi"') \\ ' String speech = "Hi"' +S::toSpaces(' String speech = "Hi"') \\ ' String speech = "Hi"' ``` ##### toTabs @@ -287,15 +287,24 @@ by $tabLength, to a tab. By default, each 4 consecutive spaces are converted to a tab. ```php -S:::toTabs(" fòô bàř") \\ " fòô bàř" +S::toTabs(" fòô bàř") \\ " fòô bàř" +``` + +##### slugify + +S::slugify(string $str) + +Converts the supplied text into an URL slug. This includes replacing +non-ASCII characters with their closest ASCII equivalents, removing +non-alphanumeric and non-ASCII characters, and replacing whitespace with +dashes. The string is also converted to lowercase. + +```php +S::slugify('Using strings like fòô bàř') // 'using-strings-like-foo-bar' ``` ## TODO -**toAnchor** - -**slugify** - **contains** **between** diff --git a/src/Stringy/Stringy.php b/src/Stringy/Stringy.php index 4d063c6..2679346 100644 --- a/src/Stringy/Stringy.php +++ b/src/Stringy/Stringy.php @@ -450,6 +450,22 @@ class Stringy { return str_replace($spaces, "\t", $str); } + /** + * Converts the supplied text into an URL slug. This includes replacing + * non-ASCII characters with their closest ASCII equivalents, removing + * non-alphanumeric and non-ASCII characters, and replacing whitespace with + * dashes. The string is also converted to lowercase. + * + * @param string $str Text to transform into an URL slug + * @return string The corresponding URL slug + */ + public static function slugify($str) { + $str = preg_replace('/[^a-zA-Z\d -]/u', '', self::standardize($str)); + $str = self::clean($str); + + return self::dasherize(strtolower($str)); + } + } ?> diff --git a/tests/Stringy/StringyTest.php b/tests/Stringy/StringyTest.php index e8d4d47..86add32 100644 --- a/tests/Stringy/StringyTest.php +++ b/tests/Stringy/StringyTest.php @@ -485,6 +485,27 @@ class StringyTestCase extends PHPUnit_Framework_TestCase { return $testData; } + /** + * @dataProvider stringsForSlugify + */ + public function testSlugify($expected, $string) { + $result = S::slugify($string); + $this->assertEquals($expected, $result); + } + + public function stringsForSlugify() { + $testData = array( + array('foo-bar', ' foo bar '), + array('foo-dbar', " Foo d'Bar "), + array('a-string-with-dashes', 'A string-with-dashes'), + array('using-strings-like-foo-bar', 'Using strings like fòô bàř'), + array('unrecognized-chars-like', 'unrecognized chars like συγγρ'), + array('numbers-1234', 'numbers 1234') + ); + + return $testData; + } + } ?>