Browse Source

Merge pull request #14010 from jeremyharris/slug-preserve-space

Fixed preserving spaces in Text::slug
Mark Story 6 years ago
parent
commit
9ff52cf29f
2 changed files with 21 additions and 3 deletions
  1. 5 3
      src/Utility/Text.php
  2. 16 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 (is_string($options['replacement']) && strlen($options['replacement']) > 0) {
+            $map[sprintf('/[%s]+/mu', $quotedReplacement)] = $options['replacement'];
+        }
         $string = preg_replace(array_keys($map), $map, $string);
 
         return $string;

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

@@ -1879,6 +1879,22 @@ 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',
+            ],
+            [
+                'Foo Bar: Not just for breakfast any-more', ['replacement' => null],
+                'FooBarNotjustforbreakfastanymore',
+            ],
+            [
+                'Foo Bar: Not just for breakfast any-more', ['replacement' => false],
+                'FooBarNotjustforbreakfastanymore',
+            ],
         ];
     }