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

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

    I wrote these two function for left and right trim of a string:

    /**
     * @param string    $str           Original string
     * @param string    $needle        String to trim from the end of $str
     * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
     * @return string Trimmed string
     */
    function rightTrim($str, $needle, $caseSensitive = true)
    {
        $strPosFunction = $caseSensitive ? "strpos" : "stripos";
        if ($strPosFunction($str, $needle, strlen($str) - strlen($needle)) !== false) {
            $str = substr($str, 0, -strlen($needle));
        }
        return $str;
    }
    
    /**
     * @param string    $str           Original string
     * @param string    $needle        String to trim from the beginning of $str
     * @param bool|true $caseSensitive Perform case sensitive matching, defaults to true
     * @return string Trimmed string
     */
    function leftTrim($str, $needle, $caseSensitive = true)
    {
        $strPosFunction = $caseSensitive ? "strpos" : "stripos";
        if ($strPosFunction($str, $needle) === 0) {
            $str = substr($str, strlen($needle));
        }
        return $str;
    }
    
    0 讨论(0)
提交回复
热议问题