Skip to content

Commit

Permalink
[8.x] Adds match and matchAll to Str (#37642)
Browse files Browse the repository at this point in the history
* Adds `match` and `matchAll` to `Str`

* CS fix
  • Loading branch information
lukeraymonddowning authored Jun 10, 2021
1 parent bf2acca commit 38d44bb
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 14 deletions.
36 changes: 36 additions & 0 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,42 @@ public static function markdown($string, array $options = [])
return $converter->convertToHtml($string);
}

/**
* Get the string matching the given pattern.
*
* @param string $pattern
* @param string $subject
* @return string
*/
public static function match($pattern, $subject)
{
preg_match($pattern, $subject, $matches);

if (! $matches) {
return '';
}

return $matches[1] ?? $matches[0];
}

/**
* Get the string matching the given pattern.
*
* @param string $pattern
* @param string $subject
* @return \Illuminate\Support\Collection
*/
public static function matchAll($pattern, $subject)
{
preg_match_all($pattern, $subject, $matches);

if (empty($matches[0])) {
return collect();
}

return collect($matches[1] ?? $matches[0]);
}

/**
* Pad both sides of a string with another.
*
Expand Down
16 changes: 2 additions & 14 deletions src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -340,13 +340,7 @@ public function markdown(array $options = [])
*/
public function match($pattern)
{
preg_match($pattern, $this->value, $matches);

if (! $matches) {
return new static;
}

return new static($matches[1] ?? $matches[0]);
return new static(Str::match($pattern, $this->value));
}

/**
Expand All @@ -357,13 +351,7 @@ public function match($pattern)
*/
public function matchAll($pattern)
{
preg_match_all($pattern, $this->value, $matches);

if (empty($matches[0])) {
return collect();
}

return collect($matches[1] ?? $matches[0]);
return Str::matchAll($pattern, $this->value);
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,18 @@ public function testStudly()
$this->assertSame('FooBarBaz', Str::studly('foo-bar_baz'));
}

public function testMatch()
{
$this->assertSame('bar', Str::match('/bar/', 'foo bar'));
$this->assertSame('bar', Str::match('/foo (.*)/', 'foo bar'));
$this->assertEmpty(Str::match('/nothing/', 'foo bar'));

$this->assertEquals(['bar', 'bar'], Str::matchAll('/bar/', 'bar foo bar')->all());

$this->assertEquals(['un', 'ly'], Str::matchAll('/f(\w*)/', 'bar fun bar fly')->all());
$this->assertEmpty(Str::matchAll('/nothing/', 'bar fun bar fly'));
}

public function testCamel()
{
$this->assertSame('laravelPHPFramework', Str::camel('Laravel_p_h_p_framework'));
Expand Down

0 comments on commit 38d44bb

Please sign in to comment.