phpstringfunctionstrposstripos

Get all occurrences of a string between two delimiters in PHP


I am using a PHP function to get all content between two delimiters in a string. However, if I have multiple occurrences of the string, it only picks up the first one. For example I'll have:

|foo| hello |foo| nothing here |foo| world |foo|

and the code will only out put "hello." My function:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = stripos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = stripos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

Solution

  • Just use preg_match_all and keep things simple:

    $input = "|foo| hello |foo| nothing here |foo| world |foo|";
    preg_match_all("/\|foo\|\s*(.*?)\s*\|foo\|/", $input, $matches);
    print_r($matches[1]);
    

    This prints:

    Array
    (
        [0] => hello
        [1] => world
    )