php,改善功能之间-添加数组支持 [英] php, get between function improvement - add array support

查看:99
本文介绍了php,改善功能之间-添加数组支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个提取2个字符串之间内容的函数.我用它来提取html标签之间的特定信息.但是,它目前只能提取第一个匹配项,因此我想知道是否有可能通过提取所有匹配项并将其提供给数组的方式进行改进.类似于preg_match_all函数.

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

推荐答案

具有递归的版本.

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

带有array_map的PHP 5.2和更低版本.

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

用于PHP 5.3的带有array_map的版本.

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

这篇关于php,改善功能之间-添加数组支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆