Skip to content

Commit 672ea02

Browse files
authored
feat: str regex functions (#528)
1 parent ce899cd commit 672ea02

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Tempest/Support/src/StringHelper.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,13 +347,27 @@ public function replace(string|array $search, string|array $replace): self
347347
return new self(str_replace($search, $replace, $this->string));
348348
}
349349

350+
public function replaceRegex(string|array $regex, string|array|callable $replace): self
351+
{
352+
if (is_callable($replace)) {
353+
return new self(preg_replace_callback($regex, $replace, $this->string));
354+
}
355+
356+
return new self(preg_replace($regex, $replace, $this->string));
357+
}
358+
350359
public function match(string $regex): array
351360
{
352361
preg_match($regex, $this->string, $matches);
353362

354363
return $matches;
355364
}
356365

366+
public function matches(string $regex): bool
367+
{
368+
return ($this->match($regex)[0] ?? null) !== null;
369+
}
370+
357371
public function ld(mixed ...$ld): void
358372
{
359373
ld($this->string, ...$ld);

src/Tempest/Support/tests/StringHelperTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,4 +267,20 @@ public function test_match(): void
267267

268268
$this->assertSame('10-', $match);
269269
}
270+
271+
public function test_matches(): void
272+
{
273+
$this->assertTrue(str('10-abc')->matches('/(?<id>\d+-)/'));
274+
$this->assertTrue(str('10-abc')->matches('/(\d+-)/'));
275+
$this->assertTrue(str('10-abc')->matches('/\d+-/'));
276+
$this->assertFalse(str('10abc')->matches('/\d+-/'));
277+
$this->assertFalse(str('abc')->matches('/\d+-/'));
278+
}
279+
280+
public function test_replace_regex(): void
281+
{
282+
$this->assertTrue(str('10-abc')->replaceRegex('/(?<id>\d+-)/', '')->equals('abc'));
283+
$this->assertTrue(str('10-abc')->replaceRegex('/(?<id>\d+-)/', fn () => '')->equals('abc'));
284+
$this->assertTrue(str('10-abc')->replaceRegex(['/\d/', '/\w/'], ['#', 'X'])->equals('##-XXX'));
285+
}
270286
}

0 commit comments

Comments
 (0)