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

时间:2015-03-20 22:23:30

标签: php string

我正在尝试在两个分隔符之间获取文本并将其保存到数组中。我写了这个函数,这个代码的问题是它删除了重复,所以

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

返回一个类似

的数组
[0] =>2,
[1]=>A,
[2] =>X ,

但我想:

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

没有正则表达式模式是否有一个substr标志,让我保持重复?这里最好的方法是什么:

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 个答案:

答案 0 :(得分:3)

使用preg_match_all()

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

输出:

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

另一种方法是使用preg_split()

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

您可以使用与上述相同的方式将其放入函数中。

答案 1 :(得分:2)

简单明了:

刚刚将所有{}更改为{并将其展开。

$str = "{2}{A2}{A}{A}{X}";
$str = array_filter(explode("{", str_replace(["{", "}"], ["", "{"], $str)));
print_r($str);

输出:

Array ( [0] => 2 [1] => A2 [2] => A [3] => A [4] => X )

为了能够识别您可以使用的空元素:

$str = "{2}{A2}{A}{A}{}{X}";
$elements = explode('}', str_replace("{", "", $str) . PHP_EOL));
array_pop($elements);
print_r($elements);

输出:

Array ( [0] =>  2  [1] =>  A2  [2] =>  A  [3] =>  A  [4] =>  [5] =>  X )