2

我有一个函数可以提取两个字符串之间的内容。我用它来提取 html 标签之间的特定信息。然而,它目前只能提取第一个匹配项,所以我想知道是否有可能以这种方式改进它以提取所有匹配项并将它们提供在一个数组中......类似于 preg_match_all 函数。

函数 get_between($content,$start,$end){
    $r = 爆炸($start, $content);
    if (isset($r[1])){
        $r = 爆炸($end, $r[1]);
   返回 $r[0];
    }
    返回 '​​';
}
4

1 回答 1

2

带有递归的版本。

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;
    }
}

带循环的版本。

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();
    }
}

PHP 5.2 及更早版本的带有 array_map 的版本。

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();
    }
}

PHP 5.3 的带有 array_map 的版本。

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();
    }
}
于 2011-06-20T12:21:04.753 回答