diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index e9eb0f99c642..8a8f1088c967 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -881,6 +881,17 @@ public static function snake($value, $delimiter = '_') return static::$snakeCache[$key][$delimiter] = $value; } + /** + * Remove all "extra" blank space from the given string. + * + * @param string $value + * @return string + */ + public static function squish($value) + { + return preg_replace('/\s+/', ' ', trim($value)); + } + /** * Determine if a given string starts with a given substring. * diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index 27175640e869..136ba388de00 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -624,6 +624,16 @@ public function scan($format) return collect(sscanf($this->value, $format)); } + /** + * Remove all "extra" blank space from the given string. + * + * @return static + */ + public function squish() + { + return new static(Str::squish($this->value)); + } + /** * Begin a string with a single instance of a given value. * diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index 5babe8698bd2..50c7c58743f7 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -538,6 +538,17 @@ public function testSnake() $this->assertSame('żółtałódka', Str::snake('ŻółtaŁódka')); } + public function testSquish() + { + $this->assertSame('laravel php framework', Str::squish(' laravel php framework ')); + $this->assertSame('laravel php framework', Str::squish("laravel\t\tphp\n\nframework")); + $this->assertSame('laravel php framework', Str::squish(' + laravel + php + framework + ')); + } + public function testStudly() { $this->assertSame('LaravelPHPFramework', Str::studly('laravel_p_h_p_framework')); diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php index 7786f2a66117..f3480970b779 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -611,6 +611,17 @@ public function testSlug() $this->assertSame('', (string) $this->stringable('')->slug()); } + public function testSquish() + { + $this->assertSame('words with spaces', (string) $this->stringable(' words with spaces ')->squish()); + $this->assertSame('words with spaces', (string) $this->stringable("words\t\twith\n\nspaces")->squish()); + $this->assertSame('words with spaces', (string) $this->stringable(' + words + with + spaces + ')->squish()); + } + public function testStart() { $this->assertSame('/test/string', (string) $this->stringable('test/string')->start('/'));