Skip to content

Commit

Permalink
Allow preserving specific non-word characters.
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Mar 24, 2016
1 parent 6ad7142 commit fff7e51
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/Utility/Text.php
Expand Up @@ -882,29 +882,36 @@ public static function transliterate($string, $transliteratorId = null)
* @param string $string the string you want to slug
* @param array $options Valid options:
* - `replacement`: Replacement string. Default '-'.
* - `transliteratorId`: A valid tranliteratorId string.
* - `transliteratorId`: A valid tranliterator id string.
* If default `null` Text::$defaultTransliteratorId to be used.
* If `false` no transliteration will be done, only non words will be removed.
* - `preserve`: Specific non-word character to preserve. Default `null`.
* For e.g. this option can be set to '.' to generate clean file names.
* @return string
*/
public static function slug($string, $options = [])
{
$options += [
'replacement' => '-',
'transliteratorId' => null
'transliteratorId' => null,
'preserve' => null
];

if ($options['transliteratorId'] !== false) {
$string = static::transliterate($string, $options['transliteratorId']);
}

$regex = '^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}';
if ($options['preserve']) {
$regex .= '(' . preg_quote($options['preserve'], '/') . ')';
}
$quotedReplacement = preg_quote($options['replacement'], '/');
$map = [
'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/[' . $regex . ']/mu' => ' ',
'/[\s]+/mu' => $options['replacement'],
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
];
$string = preg_replace(array_keys($map), array_values($map), $string);
$string = preg_replace(array_keys($map), $map, $string);

return $string;
}
Expand Down
4 changes: 4 additions & 0 deletions tests/TestCase/Utility/TextTest.php
Expand Up @@ -1722,6 +1722,10 @@ public function slugInputProvider()
'Foo Bar: Not just for breakfast any-more', ['replacement' => ''],
'FooBarNotjustforbreakfastanymore'
],
[
'clean!_me.tar.gz', ['preserve' => '.'],
'clean-me.tar.gz'
]
];
}

Expand Down

0 comments on commit fff7e51

Please sign in to comment.