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

前端 未结 7 2314
广开言路
广开言路 2020-12-14 05:04

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 :

7条回答
  •  天涯浪人
    2020-12-14 05:56

    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 "
    

提交回复
热议问题