Remove a part of a string, but only when it is at the end of the string

PhpStringReplacePreg Replace

Php Problem Overview


I need to remove a substring of a string, but only when it is at the END of the string.

for example, removing 'string' at the end of the following strings :

"this is a test string" ->  "this is a test "
"this string is a test string" - > "this string is a test "
"this string is a test" -> "this string is a test"

Any idea's ? Probably some kind of preg_replace, but how??

Php Solutions


Solution 1 - Php

You'll note the use of the $ character, which denotes the end of a string:

$new_str = preg_replace('/string$/', '', $str);

If the string is a user supplied variable, it is a good idea to run it through preg_quote first:

$remove = $_GET['remove']; // or whatever the case may be
$new_str = preg_replace('/'. preg_quote($remove, '/') . '$/', '', $str);

Solution 2 - Php

Using regexp may fails if the substring has special characters.

The following will work with any strings:

$substring = 'string';
$str = "this string is a test string";
if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));

Solution 3 - Php

I wrote these two function for left and right trim of a string:

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the end of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function rightTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle, strlen($str) - strlen($needle)) !== false) {
        $str = substr($str, 0, -strlen($needle));
    }
    return $str;
}

/**
 * @param string    $str           Original string
 * @param string    $needle        String to trim from the beginning of $str
 * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
 * @return string Trimmed string
 */
function leftTrim($str, $needle, $caseSensitive = true)
{
    $strPosFunction = $caseSensitive ? "strpos" : "stripos";
    if ($strPosFunction($str, $needle) === 0) {
        $str = substr($str, strlen($needle));
    }
    return $str;
}

Solution 4 - Php

I suppose you could use a regular expression, which would match string and, then, end of string, coupled with the preg_replace() function.


Something like this should work just fine :

$str = "this is a test string";
$new_str = preg_replace('/string$/', '', $str);


Notes :

  • string matches... well... string
  • and $ means end of string

For more informations, you can read the Pattern Syntax section of the PHP manual.

Solution 5 - Php

preg_replace and this pattern : /string\z/i

\z means end of the string

http://tr.php.net/preg_replace

Solution 6 - Php

IF you don't mind about performance AND the part of the string could be placed only at the end of string, THEN you can do this:

$string = "this is a test string";
$part = "string";
$string = implode( $part, array_slice( explode( $part, $string ), 0, -1 ) );
echo $string;
// OUTPUT: "this is a test "

Solution 7 - Php

@Skrol29's answer is the best, but here it is in function form and using the ternary operator:

if (!function_exists('str_ends_with')) {
	function str_ends_with($haystack, $suffix) {
		$length = strlen( $suffix );
		if( !$length ) {
			return true;
		}
		return substr( $haystack, -$length ) === $suffix;
	}
}

if (!function_exists('remove_suffix')) {
	function remove_suffix ($string, $suffix) {
		return str_ends_with($string, $suffix) ? substr($string, 0, strlen($string) - strlen($suffix)) : $string;
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDylanView Question on Stackoverflow
Solution 1 - PhpTim CooperView Answer on Stackoverflow
Solution 2 - PhpSkrol29View Answer on Stackoverflow
Solution 3 - PhpBasView Answer on Stackoverflow
Solution 4 - PhpPascal MARTINView Answer on Stackoverflow
Solution 5 - PhpErrico MalatestaView Answer on Stackoverflow
Solution 6 - PhpMarco PanichiView Answer on Stackoverflow
Solution 7 - PhpkloddantView Answer on Stackoverflow