2017-04-24 96 views
0

我有使用短標籤<?= $some_var; ?>的模板文件。我需要編寫一個腳本來獲得在模板中使用的變量的列表,即像一個數組:PHP preg_match_all獲取短標籤之間變量的名稱

[ 
    0 => '$some_var', 
    ... 
    n => '$some_var_n' 
] 

我曾嘗試:

preg_match_all('/<?[^p](.*)?>/s', $file_contents, $matches); 

和其他一些不同的組合,但沒有運氣。

謝謝。

+0

'preg_match_all( '/ /秒',$ file_contents,$匹配);'或'preg_match_all( '/ /秒',$ file_contents,$ matches);' –

+0

是的,@ chris85它只是變量。 – alistaircol

+0

@AlivetoDie'?'需要轉義。 – chris85

回答

1

隨着token_get_all

function genTempVar($text) { 
    $open = false; 
    foreach (token_get_all($text) as $v) { 
     if ($open) { 
      if ($v[0] == T_CLOSE_TAG) $open = false; 
      elseif ($v[0] == T_VARIABLE) yield $v[1]; 
     } elseif ($v[0] == T_OPEN_TAG_WITH_ECHO) $open = true; 
    } 
} 

print_r(iterator_to_array(genTempVar($text))); 
+0

有趣:)這對我來說是新的,看起來不錯,謝謝。 – alistaircol