Added Str::replaceMatches() (#6220)

This commit is contained in:
Deeka Wong 2023-10-18 09:12:57 +08:00 committed by GitHub
parent ceb95e1224
commit 910716d0c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 36 additions and 5 deletions

View File

@ -1,5 +1,9 @@
# v3.0.40 - TBD
## Added
- [#6220](https://github.com/hyperf/hyperf/pull/6220) Added `Hyperf\Stringable\Str::replaceMatches()`.
## Fixed
- [#6217](https://github.com/hyperf/hyperf/pull/6217) Fixed bug that `Str::replaceLast` with empty search cannot work as expected.

View File

@ -11,6 +11,7 @@ declare(strict_types=1);
*/
namespace Hyperf\Stringable;
use Closure;
use DateTimeInterface;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
@ -1001,6 +1002,24 @@ class Str
return $subject;
}
/**
* Replace the patterns matching the given regular expression.
*
* @param string $pattern
* @param Closure|string $replace
* @param array|string $subject
* @param int $limit
* @return null|string|string[]
*/
public static function replaceMatches($pattern, $replace, $subject, $limit = -1)
{
if ($replace instanceof Closure) {
return preg_replace_callback($pattern, $replace, $subject, $limit);
}
return preg_replace($pattern, $replace, $subject, $limit);
}
public static function reverse($value): string
{
return implode(array_reverse(mb_str_split($value)));

View File

@ -593,11 +593,7 @@ class Stringable implements JsonSerializable, \Stringable, ArrayAccess
*/
public function replaceMatches($pattern, $replace, $limit = -1)
{
if ($replace instanceof Closure) {
return new static(preg_replace_callback($pattern, $replace, $this->value, $limit));
}
return new static(preg_replace($pattern, $replace, $this->value, $limit));
return new static(Str::replaceMatches($pattern, $replace, $this->value, $limit));
}
/**

View File

@ -564,4 +564,10 @@ class StrTest extends TestCase
$this->assertSame('Hello earth', Str::replaceLast('world', 'earth', 'Hello world'));
$this->assertSame('Hello world', Str::replaceLast('', 'earth', 'Hello world'));
}
public function testReplaceMatches()
{
$this->assertSame('http://hyperf.io', Str::replaceMatches('/^https:\/\//', 'http://', 'https://hyperf.io'));
$this->assertSame('http://hyperf.io', Str::replaceMatches('/^https:\/\//', fn ($matches) => 'http://', 'https://hyperf.io'));
}
}

View File

@ -456,6 +456,12 @@ class StringableTest extends TestCase
$this->assertSame('foo', $this->stringable('foo')->toString());
}
public function testReplaceMatches()
{
$this->assertSame('http://hyperf.io', (string) $this->stringable('https://hyperf.io')->replaceMatches('/^https:\/\//', 'http://'));
$this->assertSame('http://hyperf.io', (string) $this->stringable('https://hyperf.io')->replaceMatches('/^https:\/\//', fn ($matches) => 'http://'));
}
/**
* @param string $string
* @return Stringable