Browse Source

Added support for preserving spaces in Text::slug

Jeremy Harris 6 years ago
parent
commit
19b315a114
2 changed files with 13 additions and 3 deletions
  1. 5 3
      src/Utility/Text.php
  2. 8 0
      tests/TestCase/Utility/TextTest.php

+ 5 - 3
src/Utility/Text.php

@@ -1170,16 +1170,18 @@ class Text
             $string = static::transliterate($string, $options['transliteratorId']);
         }
 
-        $regex = '^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}';
+        $regex = '^\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 = [
-            '/[' . $regex . ']/mu' => ' ',
-            '/[\s]+/mu' => $options['replacement'],
+            '/[' . $regex . ']/mu' => $options['replacement'],
             sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
         ];
+        if ($options['replacement']) {
+            $map[sprintf('/[%s]+/mu', $quotedReplacement)] = $options['replacement'];
+        }
         $string = preg_replace(array_keys($map), $map, $string);
 
         return $string;

+ 8 - 0
tests/TestCase/Utility/TextTest.php

@@ -1879,6 +1879,14 @@ HTML;
                 'cl#e|an(me.jpg', ['preserve' => '.'],
                 'cl-e-an-me.jpg',
             ],
+            [
+                'Foo Bar: Not just for breakfast any-more', ['preserve' => ' '],
+                'Foo Bar- Not just for breakfast any-more',
+            ],
+            [
+                'Foo Bar: Not just for (breakfast) any-more', ['preserve' => ' ()'],
+                'Foo Bar- Not just for (breakfast) any-more',
+            ],
         ];
     }