Skip to content Skip to sidebar Skip to footer

Php, Get Between Function Improvement - Add Array Support

I have a function which extracts the content between 2 strings. I use it to extract specific information between html tags . However it currently works to extract only the first ma

Solution 1:

Version with recursion.

functionget_between($content,$start,$end,$rest = array()){
    $r = explode($start, $content, 2);
    if (isset($r[1])){
        $r = explode($end, $r[1], 2);
        $rest[] = $r[0];
        return get_between($r[1],$start,$end,$rest);
    } else {
        return$rest;
    }
}

Version with loop.

functionget_between($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        array_shift($r);
        $ret = array();
        foreach ($ras$one) {
            $one = explode($end,$one);
            $ret[] = $one[0];
        }
        return$ret;
    } else {
        returnarray();
    }
}

Version with array_map for PHP 5.2 and earlier.

functionget_between_help($end,$r){
    $r = explode($end,$r);
    return$r[0];   
}

functionget_between($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        array_shift($r);
        $end = array_fill(0,count($r),$end);
        $r = array_map('get_between_help',$end,$r);
        return$r;
    } else {
        returnarray();
    }
}

Version with array_map for PHP 5.3.

functionget_between($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        array_shift($r);
        $help_fun = function($arr) use ($end) {
            $r = explode($end,$arr);
            return$r[0];
        };
        $r = array_map($help_fun,$r);
        return$r;
    } else {
        returnarray();
    }
}

Post a Comment for "Php, Get Between Function Improvement - Add Array Support"