php:我想从“w; h;”中修剪“h;”以获得“w”; 但我得到的是“w”

The below program is to right trim the string "w;h;" off string "h;" to get "w;". But unexpectedly what I got is "w", not "w;".

<?php

        $string="w;h;";
        $str="h;";
        $nStr=rtrim($string,$str);
        echo $nStr.'</br>';

 ?>

Use str_replace http://php.net/manual/en/function.str-replace.php

$string="w;h;";
$str="h;";
Echo str_replace($str, "", $string);

https://3v4l.org/P9Hbe

Str_replace replaces $str with nothing. Leaving w;

From the manual:

character_mask

Optionally, the stripped characters can also be specified using the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

If you do rtrim("w;h;", "h;") you're saying "trim either h or ; from the end of the string, meaning cut off characters that are either h or ; in this case it will cut off characters until it is only left with w.

If you want to remove a specific string from the end you have to do something like:

if (substr($string,-strlen($str)) == $str) {
    $string = substr($string,0,-strlen($str));
}

Note: This assumes ASCII strings. For UTF-8 multibyte strings use mb_substr .