【问题标题】:php, get between function improvement - add array supportphp, get between 函数改进 - 添加数组支持
【发布时间】:2011-09-18 15:36:52
【问题描述】:

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

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

【问题讨论】:

    标签: php regex html-content-extraction


    【解决方案1】:

    递归版本。

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

    带有 array_map 的 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2016-06-18
      • 2018-04-16
      相关资源
      最近更新 更多