PHP extract string between delimiters allow duplicates -
i'm trying text between 2 delimiters , save array. wrote function, problem code removes duplicates
$this->getinnersubstring('{2}{a}{a}{a}{x}','{', '}');
returns array
[0] =>2, [1]=>a, [2] =>x ,
yet want:
[0] =>2, [1]=>a, [2]=>a, [3]=>a, [4] =>x,
without regex patterns there substr flag lets me keep duplicates? what's best approach here:
function getinnersubstring($string,$start, $end){ $s = array(); { $startpos = strpos($string, $start) + strlen($start); $endpos = strpos($string, $end, $startpos); $s[] = substr($string, $startpos, $endpos - $startpos); //remove entire occurance 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; }
use preg_match_all()
that:
$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]; }
output:
array(5) { [0]=> string(1) "2" [1]=> string(1) "a" [2]=> string(1) "a" [3]=> string(1) "a" [4]=> string(1) "x" }
an alternative use preg_split()
:
var_dump(preg_split('({|})', $string, -1, preg_split_no_empty));
you can put function using same way above.
Comments
Post a Comment