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

前端 未结 7 2312
广开言路
广开言路 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);
    
    0 讨论(0)
  • 2020-12-14 05:53

    You can use rtrim().

    php > echo rtrim('this is a test string', 'string');
    this is a test 
    

    This will work only in some cases, as 'string' is just a characters mask and char order will not be respected.

    0 讨论(0)
  • 2020-12-14 05:56

    preg_replace and this pattern : /string\z/i

    \z means end of the string

    http://tr.php.net/preg_replace

    0 讨论(0)
  • 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 "
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题