Skip to content

Commit

Permalink
Making str_starts_with and str_ends_with more durable.
Browse files Browse the repository at this point in the history
  • Loading branch information
maximkott committed Mar 15, 2016
1 parent 69eebd0 commit 8c44110
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/string.php
Expand Up @@ -74,13 +74,23 @@ function str_ends_with($string, $search, $caseSensitive = false) {
return false;
}

$match = substr($string, -strlen($search));
if ( ! is_array($search)) {
$search = [$search];
}

if ($caseSensitive) {
return $match == $search;
foreach ($search as $item) {
$match = substr($string, -strlen($item));

if ($caseSensitive) {
if ($match == $item) {
return true;
}
} else if(strcasecmp($match, $item) === 0) {
return true;
}
}

return strcasecmp($match, $search) === 0;
return false;
}
}

Expand Down
5 changes: 5 additions & 0 deletions tests/StringTest.php
Expand Up @@ -58,6 +58,11 @@ public function test_ends_with($expected, $string, $starts, $ends, $caseSensitiv
$this->assertEquals($expected, str_ends_with($string, $ends, $caseSensitive));
}

public function test_ends_with_array() {
$this->assertTrue(str_starts_with('foo', ['o', 'b', 'f']));
$this->assertFalse(str_starts_with('foo', ['a', 'b','c']));
}

public function test_ends_with_on_non_string() {
$this->assertFalse(str_ends_with([], 'a'));
}
Expand Down

0 comments on commit 8c44110

Please sign in to comment.