awholegnuworld
awholegnuworld

Reputation: 411

Get all occurrences of a string between two delimiters in PHP

I am using a PHP function to get all content between two delimiters in a string. However, if I have multiple occurrences of the string, it only picks up the first one. For example I'll have:

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

and the code will only out put "hello." My function:

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

Upvotes: -2

Views: 482

Answers (2)

StackSlave
StackSlave

Reputation: 10627

Little late, but here's my two cents:

<?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|');
?>

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

Just use preg_match_all and keep things simple:

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

This prints:

Array
(
    [0] => hello
    [1] => world
)

Upvotes: 1

Related Questions