Skip to content

Commit 1bcea14

Browse files
Added Str::containsIgnoreCase() (#5971)
Co-authored-by: 李铭昕 <[email protected]>
1 parent 9f56aac commit 1bcea14

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

src/Str.php

+24-4
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,12 @@ public static function charAt($subject, $index)
208208
*
209209
* @param array|string $needles
210210
*/
211-
public static function contains(string $haystack, $needles): bool
211+
public static function contains(string $haystack, mixed $needles, bool $ignoreCase = false): bool
212212
{
213+
if ($ignoreCase) {
214+
return static::containsIgnoreCase($haystack, $needles);
215+
}
216+
213217
foreach ((array) $needles as $needle) {
214218
$needle = (string) $needle;
215219
if ($needle !== '' && str_contains($haystack, $needle)) {
@@ -220,17 +224,33 @@ public static function contains(string $haystack, $needles): bool
220224
return false;
221225
}
222226

227+
/**
228+
* Determine if a given string contains a given substring regardless of case sensitivity.
229+
*
230+
* @param array|string $needles
231+
*/
232+
public static function containsIgnoreCase(string $haystack, $needles): bool
233+
{
234+
foreach ((array) $needles as $needle) {
235+
$needle = (string) $needle;
236+
if ($needle !== '' && stripos($haystack, $needle) !== false) {
237+
return true;
238+
}
239+
}
240+
241+
return false;
242+
}
243+
223244
/**
224245
* Determine if a given string contains all array values.
225246
*
226-
* @param string $haystack
227247
* @param string[] $needles
228248
* @return bool
229249
*/
230-
public static function containsAll($haystack, array $needles)
250+
public static function containsAll(string $haystack, array $needles, bool $ignoreCase = false)
231251
{
232252
foreach ($needles as $needle) {
233-
if (! static::contains($haystack, $needle)) {
253+
if (! static::contains($haystack, $needle, $ignoreCase)) {
234254
return false;
235255
}
236256
}

tests/StrTest.php

+7
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,7 @@ public function testIsMatch()
251251

252252
public function testContains()
253253
{
254+
$this->assertTrue(Str::contains('Hyperf', ['h'], true));
254255
$this->assertTrue(Str::contains('Hyperf', ['H']));
255256
$this->assertFalse(Str::contains('Hyperf', ['']));
256257
$this->assertFalse(Str::contains('Hyperf', [null]));
@@ -264,4 +265,10 @@ public function testEndsWith()
264265
$this->assertFalse(Str::endsWith('Hyperf', [null]));
265266
$this->assertFalse(Str::endsWith('Hyperf', null));
266267
}
268+
269+
public function testContainsAll()
270+
{
271+
$this->assertTrue(Str::containsAll('Hyperf', ['h'], true));
272+
$this->assertFalse(Str::containsAll('Hyperf', ['h']));
273+
}
267274
}

0 commit comments

Comments
 (0)