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

前端 未结 7 2315
广开言路
广开言路 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 06:04

    Using regexp may fails if the substring has special characters.

    The following will work with any strings:

    $substring = 'string';
    $str = "this string is a test string";
    if (substr($str,-strlen($substring))===$substring) $str = substr($str, 0, strlen($str)-strlen($substring));
    

提交回复
热议问题