如何在PHP中从右修剪字符串?

Sum*_*Rai 1 php string trim

我有一个字符串示例

this-is-the-example/exa
Run Code Online (Sandbox Code Playgroud)

我想从上面一行修剪/ exa

$string1 = "this-is-the-example/exa";
$string2 = "/exa";
Run Code Online (Sandbox Code Playgroud)

我在用 rtrim($string1, $sting2)

但是输出是 this-is-the-exampl

我想this-is-the-example作为输出。

这两个字符串都是动态的,并且在字符串中可能多次出现。但是我只想删除最后一部分。同样不是强制性的string2 /在其中。这也可能是正常的字符串。像aabc太..

meg*_*382 5

您可以使用多种方法:

使用substrDEMO):

function removeFromEnd($haystack, $needle)
{
    $length = strlen($needle);

    if(substr($haystack, -$length) === $needle)
    {
        $haystack = substr($haystack, 0, -$length);
    }
    return $haystack;
}


$trim = '/exa';
$str = 'this-is-the-example/exa';


var_dump(removeFromEnd($str, $trim));
Run Code Online (Sandbox Code Playgroud)

使用正则表达式(DEMO):

$trim = '/exa';
$str = 'this-is-the-example/exa';

function removeFromEnd($haystack, $needle)
{
    $needle = preg_quote($needle, '/');
    $haystack = preg_replace("/$needle$/", '', $haystack);
    return $haystack;
}
var_dump(removeFromEnd($str, $trim));
Run Code Online (Sandbox Code Playgroud)