Search code examples
phpstrpos

Cut String before the first appearence BEFORE another string2


I would like to cut a string in a specific way:

$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";

Now I would like to check backwards of "EXAMPLE" and would cut everything before the FIRST appearance of "a". The difficulty is that the number of "a" is unknown and can appear multiple times. It has to be the last "a" from where the string is shown.

So the result would be:

a very long string. This is a very long EXAMPLE

I just could manage to get a StringBetween function with strpos but I am not able to manage this problem above.

thank you very much!


Solution

  • Did you try using RegEx for the function instead of 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"));