Having trouble returning an array of positions:
function returnPosition($string,$start){
preg_match('/' . preg_quote($start, '/').'/im', $string, $m, PREG_OFFSET_CAPTURE);
$startArr = array();
foreach ($m as $value)
{
$startArr = array_push($startArr, $m);
}
//var_dump($startArr);
return $startArr;
}
Thanks
No surprise, you're using array_push wrong. It does NOT return the modified array. It returns the new number of elements in the array, so on each iteration you're trashing what used to be an array with an int. Try
$startArr[] = $m;
or at least just
array_push($startArr, $m);
with no assignment at all.
Found something that works for me:
function getTagPositions($strBody, $start, $end)
{
preg_match_all('/' . preg_quote($start, '/') . '([\w\s.]*?)'. preg_quote($end, '/').'/im', $strBody, $strTag, PREG_PATTERN_ORDER);
$intOffset = 0;
$intIndex = 0;
$intTagPositions = array();
foreach($strTag[0] as $strFullTag) {
$intTagPositions[$intIndex] = array('start' => (strpos($strBody, $strFullTag, $intOffset)), 'end' => (strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag)));
$intOffset += strlen($strFullTag);
$intIndex++;
}
return $intTagPositions;
}
$intTagPositions = getTagPositions("hello there hello hello","he","lo");
// returns
Array ( [0] => Array ( [start] => 0 [end] => 5 ) [1] => Array ( [start] => 7 [end] => 17 ) [2] => Array ( [start] => 18 [end] => 23 ) )