-2

我正在使用 PHP 函数来获取字符串中两个分隔符之间的所有内容。但是,如果我多次出现该字符串,它只会选择第一个。例如,我将拥有:

|foo| hello |foo| nothing here |foo| world |foo|

并且代码只会输出“你好”。我的功能:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = stripos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = stripos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}
4

2 回答 2

1

只需使用preg_match_all并保持简单:

$input = "|foo| hello |foo| nothing here |foo| world |foo|";
preg_match_all("/\|foo\|\s*(.*?)\s*\|foo\|/", $input, $matches);
print_r($matches[1]);

这打印:

Array
(
    [0] => hello
    [1] => world
)
于 2021-05-19T23:47:18.777 回答
1

有点晚了,但这是我的两分钱:

<?php 
function between($string, $start = '|', $end = null, $trim = true){
  if($end === null)$end = $start;
  $trim = $trim ? '\\s*' : '';
  $m = preg_split('/'.$trim.'(\\'.$start.'|\\'.$end.')'.$trim.'/i', $string);
  return array_filter($m, function($v){
    return $v !== '';
  });
}
$test = between('|foo| hello |foo| nothing here |foo| world |foo|');
?>
于 2021-05-20T00:38:23.570 回答