douguanci9158 2015-03-20 22:23
浏览 123
已采纳

PHP在分隔符之间提取字符串允许重复

I'm trying to get the text between two delimiters and save it into an array. I wrote this function, the problem with this code is it removes duplicates so

$this->getInnerSubstring('{2}{A}{A}{A}{X}','{', '}');

returns an array that is like

[0] =>2,
[1]=>A,
[2] =>X ,

Yet I want:

[0] =>2,
[1]=>A,
[2]=>A,
[3]=>A,
[4] =>X,

Without Regex patterns is there a substr flag that lets me keep duplicates? what's the best approach here:

function getInnerSubstring($string,$start, $end){
    $s = array();
        do
         {
             $startpos = strpos($string, $start) + strlen($start);
             $endpos = strpos($string, $end, $startpos);
             $s[] = substr($string, $startpos, $endpos - $startpos);
                //remove entire occurance from string:
                $string =   str_replace(substr($string, strpos($string, $start), strpos($string, $end) +strlen($end)), '', $string);


        }
    while (strpos($string, $start)!== false && strpos($string, $end)!== false);


    return $s;

    }
  • 写回答

2条回答 默认 最新

  • dongzhiman2162 2015-03-20 22:29
    关注

    Use preg_match_all() for that:

    $string = "{2}{A}{A}{A}{X}";
    $ldelim = "{";
    $rdelim = "}";
    
    var_dump(getInnerSubstring($string, $ldelim, $rdelim));
    
    function getInnerSubstring($string, $ldelim, $rdelim) {
        $pattern = "/" . preg_quote($ldelim) . "(.*?)" . preg_quote($rdelim) . "/";
        preg_match_all($pattern, $string, $matches);
        return $matches[1];
    }
    

    output:

    array(5) {
      [0]=>
      string(1) "2"
      [1]=>
      string(1) "A"
      [2]=>
      string(1) "A"
      [3]=>
      string(1) "A"
      [4]=>
      string(1) "X"
    }
    

    An alternative would be to use preg_split():

    var_dump(preg_split('({|})', $string, -1, PREG_SPLIT_NO_EMPTY));
    

    You can put that into a function using the same way as above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?