Preg_match使用PREG_OFFSET_CAPTURE返回每个匹配的位置数组

时间:2012-12-11 21:16:44

标签: php function preg-match

无法返回一系列职位:

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

由于

2 个答案:

答案 0 :(得分:2)

毫不奇怪,你是using array_push wrong NOT 返回修改后的数组。它返回数组中新的元素数,因此在每次迭代时,您都会废弃曾经是int的数组。尝试

$startArr[] = $m;

或至少只是

array_push($startArr, $m);

完全没有作业。

答案 1 :(得分:0)

找到适合我的东西:

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