php, get between function improvement - add array support

六眼飞鱼酱① 提交于 2020-01-04 06:13:05

问题


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 match so I would like to know if it would be possible to improve it in a such way to extract all the matches and provide them in an array .. similar with preg_match_all function .

function get_between($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
   return $r[0];
    }
    return '';
}

回答1:


Version with recursion.

function get_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.

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

Version with array_map for PHP 5.2 and earlier.

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

function get_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 {
        return array();
    }
}

Version with array_map for PHP 5.3.

function get_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 {
        return array();
    }
}


来源:https://stackoverflow.com/questions/6410942/php-get-between-function-improvement-add-array-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!