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

前端 未结 7 2316
广开言路
广开言路 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条回答
  •  -上瘾入骨i
    2020-12-14 06:05

    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.

提交回复
热议问题