Skip to content

Commit

Permalink
[10.x] Add Str::unwrap (#49779)
Browse files Browse the repository at this point in the history
* Add Str::unwrap

* Add "unwrap" to stringable

* Add more tests
  • Loading branch information
stevebauman committed Jan 22, 2024
1 parent e364c47 commit cb9983c
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Illuminate/Support/Str.php
Expand Up @@ -390,6 +390,27 @@ public static function wrap($value, $before, $after = null)
return $before.$value.($after ??= $before);
}

/**
* Unwrap the string with the given strings.
*
* @param string $value
* @param string $before
* @param string|null $after
* @return string
*/
public static function unwrap($value, $before, $after = null)
{
if (static::startsWith($value, $before)) {
$value = static::substr($value, static::length($before));
}

if (static::endsWith($value, $after ??= $before)) {
$value = static::substr($value, 0, -static::length($after));
}

return $value;
}

/**
* Determine if a given string matches a given pattern.
*
Expand Down
12 changes: 12 additions & 0 deletions src/Illuminate/Support/Stringable.php
Expand Up @@ -1224,6 +1224,18 @@ public function wrap($before, $after = null)
return new static(Str::wrap($this->value, $before, $after));
}

/**
* Unwrap the string with the given strings.
*
* @param string $before
* @param string|null $after
* @return static
*/
public function unwrap($before, $after = null)
{
return new static(Str::unwrap($this->value, $before, $after));
}

/**
* Convert the string into a `HtmlString` instance.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Support/SupportStrTest.php
Expand Up @@ -425,6 +425,15 @@ public function testWrap()
$this->assertEquals('foo-bar-baz', Str::wrap('-bar-', 'foo', 'baz'));
}

public function testUnwrap()
{
$this->assertEquals('value', Str::unwrap('"value"', '"'));
$this->assertEquals('value', Str::unwrap('"value', '"'));
$this->assertEquals('value', Str::unwrap('value"', '"'));
$this->assertEquals('bar', Str::unwrap('foo-bar-baz', 'foo-', '-baz'));
$this->assertEquals('some: "json"', Str::unwrap('{some: "json"}', '{', '}'));
}

public function testIs()
{
$this->assertTrue(Str::is('/', '/'));
Expand Down
7 changes: 7 additions & 0 deletions tests/Support/SupportStringableTest.php
Expand Up @@ -1177,6 +1177,13 @@ public function testWrap()
$this->assertEquals('"value"', $this->stringable('value')->wrap('"'));
}

public function testUnwrap()
{
$this->assertEquals('value', $this->stringable('"value"')->unwrap('"'));
$this->assertEquals('bar', $this->stringable('foo-bar-baz')->unwrap('foo-', '-baz'));
$this->assertEquals('some: "json"', $this->stringable('{some: "json"}')->unwrap('{', '}'));
}

public function testToHtmlString()
{
$this->assertEquals(
Expand Down

0 comments on commit cb9983c

Please sign in to comment.