-2

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);
}
awholegnuworld
  • 381
  • 1
  • 12
  • 1
    What arguments are you calling with? What is the expected result? – Barmar May 19 '21 at 23:37
  • You have no loop in your code. How do you expect it to return multiple things? – Barmar May 19 '21 at 23:38
  • String position functions only return the first occurrence they find. You might want to look into regular expressions. – El_Vanja May 19 '21 at 23:40
  • You can use `strripos()` to find the last occurrence of a string. Use that to find `$end`. – Barmar May 19 '21 at 23:45
  • Does this answer your question? [Get string between - Find all occurrences PHP](https://stackoverflow.com/questions/27078259/get-string-between-find-all-occurrences-php) – El_Vanja May 19 '21 at 23:46
  • @El_Vanja I get this, Warning: strpos() expects parameter 1 to be string, array given – awholegnuworld May 20 '21 at 00:04

2 Answers2

1

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
)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

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|');
?>
StackSlave
  • 10,613
  • 2
  • 18
  • 35