如何从 PHP 的右边 trim 字符串?

How to trim string from right in PHP?

我有一个字符串示例

this-is-the-example/exa

我想从上面的行trim /exa

$string1 = "this-is-the-example/exa";
$string2 = "/exa";

我正在使用rtrim($string1, $sting2)

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

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

两个字符串都是动态的,可能在字符串中多次出现。但我只想删除最后一部分。 string2 中有 / 也不是强制性的。这也可能是普通字符串。也喜欢 aabc..

你可以使用爆炸

<?php

$x = "this-is-the-example/exa";

$y = explode('/', $x);

echo $y[0];

rtrim 的第二个参数是一个字符掩码而不是一个字符串,你的最后一个 "e" 被修剪了,这是正常的。

考虑使用其他东西,例如正则表达式 (preg_replace) 来满足您的需要

这会保留“/”字符之前的所有内容:

$str = preg_replace('/^([^\/]*).*/','', 'this-is-the-example/exa');

这将删除最后一部分。

$str = preg_replace('/^(.*)\/.*$/','', 'this-is-the-example/exa/mple');

首先 explode 字符串,使用 array_pop 从展开的数组中删除最后一个元素,然后 implode 使用 / 再次返回。

$str = "this-is-the-example/exa";
if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}

如果 URL 中有多个 /,这将起作用,并且只会删除最后一个元素。

$str = "this-is-the-example/somevalue/exa";

if(strpos($str, '/') !== false)
{
    $arr = explode('/', $str);
    array_pop($arr);
    $str = implode('/', $arr);
    // output this-is-the-example
}

允许错误处理,如果在搜索字符串中找不到子字符串...

<?php

$myString = 'this-is-the-example/exa';

//[Edit: see comment below] use strrpos, not strpos, to find the LAST occurrence 
$endPosition = strrpos($myString, '/exa');

// TodO; if endPosition === False then handle error, substring not found 

$leftPart = substr($myString, 0, $endPosition);

echo($leftPart);

?>

产出

this-is-the-example

strstr()问好

$str = 'this-is-the-example/exa';
$trim = '/exa';
$result = strstr($str, $trim, true);
echo $result;

您可以使用多种方法:

substr(DEMO):

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));

使用正则表达式(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));

希望这对您有所帮助。 :)

只需尝试此代码:

<?php
$this_example = substr("this-is-the-example/exa", 0, -4);  
echo "<br/>".$this_example; // returns "this-is-the-example"
?>