PHP - 删除最后一次出现后的所有内容,并选择删除针

时间:2017-04-15 20:12:16

标签: php string function

我试图创建一个函数来删除从最后一个单词出现到字符串结尾的所有内容,同时还可以选择删除该单词。

例如,如果我在中搜索 cheese ,奶酪是好的,奶酪是美味的,那么是美味的将被删除。< / p>

但我也想要一个选项来删除我搜索过的单词。在那种情况下,我最终得到奶酪是好的

我有一个很好的函数,可以从带有选项的字符串的开头执行此操作。它看起来像这样......但我似乎无法做到相反。

function remove_before($needle, $haystack, $removeNeedle=false) {
    $pos = strpos($haystack, $needle);
    if ($pos!==false)
        return substr($haystack, $pos + (strlen($needle) * $removeNeedle) );
    else
        return $haystack;
}

3 个答案:

答案 0 :(得分:4)

使用以下remove_after()功能:

function remove_after($needle, $haystack, $removeNeedle = false) {
    // getting the position of the last occurence of `$needle`
    $last_pos = strrpos($haystack, $needle);
    // if the `$needle` is found within `$haystack`
    if (($last_pos = strrpos($haystack, $needle)) !== false) {
        return substr($haystack, 0, $removeNeedle? $last_pos : $last_pos + strlen($needle));
    }
    return $haystack;
}

var_dump(remove_after("cheese", "The cheese is good and the cheese is yummy"));
var_dump(remove_after("cheese", "The cheese is good and the cheese is yummy", true)); 

输出:

string(33) "The cheese is good and the cheese"
string(27) "The cheese is good and the "

答案 1 :(得分:1)

我认为这解决了这个问题:

function remove_before($needle, $haystack, $removeNeedle=false) {
    $pos = strrpos($haystack, $needle);
    if ( !($pos === false) ) {
        if( !$removeNeedle )
            $pos += strlen($needle);
        $haystack = substr($haystack, 0, $pos);
    }
    return $haystack;
}

var_dump(remove_before("cheese", "The cheese is good and the cheese is yummy", true));
// Outputs: "The cheese is good and the "

var_dump(remove_before("cheese", "The cheese is good and the cheese is yummy"));
// Outputs: "The cheese is good and the cheese"

答案 2 :(得分:0)

我想出了我原本想要解决问题的方法。类似于我的remove_before函数....由于keepNeedle将是1或0,你可以简单地将它乘以你的子字符串,这样你就不需要多个If Else语句。

function remove_after($needle, $haystack, $keepNeedle=true) {
$last_pos = strrpos($haystack, $needle);
if ($last_pos!== false) return substr($haystack,0,$last_pos+(strlen($needle)*$keepNeedle));
return $haystack;}