diff --git a/CHANGELOG.md b/CHANGELOG.md index ba141bd..c2dd687 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] +## [2.3.0] - 2018-12-18 +### Added +- New feature `StringTools::removeEnd` + ## [2.2.0] - 2018-07-13 ### Added - New `ArrayTools` class helper diff --git a/README.md b/README.md index 54e1e65..282e3da 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,17 @@ StringTools::removeStart($str, $toRemove) : string * `$str` string input * `$toRemove` string to remove at the start of `$str` +#### ::removeEnd + +Removes the end of the string if it matches with the given text to remove. + +```php +StringTools::removeEnd($str, $toRemove) : string +``` + +* `$str` string input +* `$toRemove` string to remove at the end of `$str` + #### ::contains ```php @@ -137,4 +148,4 @@ DateTimeComparator::lowest($dateTime1, $dateTime2) : ?\DateTimeInterface ``` * `$dateTime1` The first \DateTimeInterface or null -* `$dateTime2` The second \DateTimeInterface or null \ No newline at end of file +* `$dateTime2` The second \DateTimeInterface or null diff --git a/spec/Nekland/Tools/StringToolsSpec.php b/spec/Nekland/Tools/StringToolsSpec.php index c7ee34f..7178f42 100644 --- a/spec/Nekland/Tools/StringToolsSpec.php +++ b/spec/Nekland/Tools/StringToolsSpec.php @@ -83,4 +83,11 @@ function it_should_uppercase_first_letter_with_ucfirst() $this::mb_ucfirst('HelloWorld')->shouldReturn('HelloWorld'); $this::mb_ucfirst('🍕isReallyGood')->shouldReturn('🍕isReallyGood'); } + + function it_should_remove_given_end_of_string() + { + $this::removeEnd('I\'m some random text with end to remove', 'end to remove')->shouldReturn('I\'m some random text with '); + $this::removeEnd('I like 🍪 so I remove 🍕', ' so I remove 🍕')->shouldReturn('I like 🍪'); + $this::removeEnd('I like pizza', ' and cookies')->shouldReturn('I like pizza'); + } } diff --git a/src/StringTools.php b/src/StringTools.php index b72c054..6c39247 100644 --- a/src/StringTools.php +++ b/src/StringTools.php @@ -72,6 +72,21 @@ public static function removeStart($str, $toRemove) return substr($str, $sizeToRemove, strlen($str) - $sizeToRemove); } + /** + * @param string $str + * @param string $toRemove + * @return string + */ + public static function removeEnd($str, $toRemove) + { + if (!StringTools::endsWith($str, $toRemove)) { + return $str; + } + $sizeToRemove = strlen($toRemove); + + return substr($str, 0, - $sizeToRemove); + } + /** * @param string $str The string that should contains the needle * @param string $needle What should be contained