在第一次出现之前剪切字符串 BEFORE 另一个字符串 2

Cut String before the first appearence BEFORE another string2

我想以特定方式剪切字符串:

$string1 = "...This is a very long an complex string .
This is a very long string. This is a very long EXAMPLE string. 
This is a very long string. This is a very long string.";

$string2 = "EXAMPLE";

现在我想向后检查 "EXAMPLE" 并在 "a" 第一次出现之前删除所有内容。难点在于"a"的个数未知,可以出现多次。它必须是显示字符串的最后一个 "a"。

所以结果是:

一个很长的字符串。这是一个很长的例子

我只能设法通过 strpos 获得 StringBetween 函数,但我无法解决上述问题。

非常感谢!

您是否尝试过使用 RegEx 作为函数而不是 strpos

<?php

function str_between($string, $start, $end, $flags = "mi") {
    $pattern = "/(?<={$start})(.*)(?={$end})/{$flags}";
    preg_match($pattern, $string, $matches);

    return $matches[0];
}

$string1 = "...This is a very long an complex string .
This is a very long string. This is a very long EXAMPLE string. 
This is a very long string. This is a very long string.";


var_dump(str_between($string1, "a", "EXAMPLE"));

我创建了一个组合使用 reverse() 和 substr() 的解决方案,从第一个字符串到第二个字符串的最接近出现处全部切断。