开发者

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

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 s开发者_运维知识库tring" - > "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??


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 and follows conventions used by built-in string functions:

function right_trim(string $haystack, string $needle): string {
    $needle_length = strlen($needle);
    if (substr($haystack, -$needle_length) === $needle) {
        return substr($haystack, 0, -$needle_length);
    }
    return $haystack;
}


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


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.


preg_replace and this pattern : /string\z/i

\z means end of the string

http://tr.php.net/preg_replace


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 "


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


PHP 8 version

function removePostfix(string $haystack, string $needle): string
{
    if (str_ends_with($haystack, $needle)) {
        return substr($haystack, 0, strlen($haystack) - strlen($needle));
    }


    return $haystack;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜