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

前端 未结 7 2317
广开言路
广开言路 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:43

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

提交回复
热议问题