Reputation: 411
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
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
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