php – How to get the last occurrence of a string?

php – How to get the last occurrence of a string?

As mentioned in my comment, swap out strpos() for strrpos()

Find the numeric position of the last occurrence of needle in the haystack string.

Also, I believe you should change

if ($ini == 0)

to

if ($ini === false)

The former will match if $start is at the very beginning of $string. The latter will match if $start cannot be found at all.

Demo ~ https://eval.in/1027283

I took the liberty to rewrote your code, to make it, IMHO, more readable and self-explanatory 🙂

Id also recommend you to use the strrpos:

function getStringBetween($string, $start, $end) {
    $lastStartIndex = strrpos($string, $start);
    $lastEndIndex = strrpos($string, $end);

    $substringStartIndex = $lastStartIndex + strlen($start);
    $substringSize = $lastStartIndex - $lastEndIndex - 1;

    return substr($string, $substringStartIndex, $substringSize);
}

$text = John has 13 oranges and Jane has 8 oranges;
$how_many_oranges = getStringBetween($text, has, oranges);
echo  . $how_many_oranges . ; // echos  8 

php – How to get the last occurrence of a string?

Try this:

function get_string_between($string, $start, $end){
    $p1 = explode($start,$str);
    for($i=1;$i<count($p1);$i++){
        $p2 = explode($end,$p1[$i]);
        $p[] = $p2[0];
    }
    return $p;
}

source: stackoverflow.com/a/45033158

Leave a Reply

Your email address will not be published. Required fields are marked *