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

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


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);


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));


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;}