Mid-Atlantic Developer Conference - Call for Speakers


(PHP 4 >= 4.2.0, PHP 5, PHP 7)

token_get_allBelirtilen kaynağı PHP dizgeciklerine ayırır


array token_get_all ( string $kaynak )

Belirtilen kaynak dizgesi, Zend motorunun sözdizimsel tarayıcısı kullanılarak PHP dil dizgeciklerine çözümlenir.

Dizgeciklerin listesi için Çözümleyici Dizgeciklerinin Listesi sayfasına bakınız veya bir dizgecik değerini dizgesel gösterimine dönüştürmek için token_name() işlevini kullanınız.



Çözümlenecek PHP kaynak kodu.

Dönen Değerler

Dizgecik betimleyicilerinden oluşan bir dizi. Her dizgecik betimleyicisi ya tek bir karakterden (;, ., >, ! gibi) oluşur ya da üç elemanlı bir diziden; 0. elemanda dizgecik indisi, 1. elemanda özgün dizgeciğin dizgesel içeriği ve 2. elemanda satır numarası bulunur.


Örnek 1 - token_get_all() örnekleri

token_get_all('<?php echo; ?>');
/* => array(
             array(T_OPEN_TAG, '<?php'),
             array(T_ECHO, 'echo'),
             array(T_CLOSE_TAG, '?>') ); */

/* Aşağıdaki örnekte dizge beklendiği gibi
   T_COMMENT (PHP <5'te' T_ML_COMMENT) olarak değil
   T_INLINE_HTML olarak çözümlenmektedir. Bunun sebebi
   sağlanan kodda hiçbir ama/kapama etiketinin bulunmayışıdır.
   Bu, normal bir dosyada <?php ?> etiketlerinin dışına
   bir açıklama koymaya eşdeğerdir. */
$tokens token_get_all('/* açıklama */');
// => array(array(T_INLINE_HTML, '/* comment */'));

Sürüm Bilgisi

Sürüm: Açıklama
5.2.2 Satır numaraları 2. elemanda dönmeye başladı.

add a note add a note

User Contributed Notes 7 notes

gomodo at free dot fr
8 years ago
Yes, some problems (On WAMP, PHP 5.3.0 ) with get_token_all()

1 : bug line numbers
Since PHP 5.2.2 token_get_all()  should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it work perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() ,  sometimes you find wrongs line numbers  (return next line)... :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex : php code line by line) :
for example if a comment tag is not closed  token_get_all()  can block loops on this  warning :
Warning: Unterminated comment starting line

This problem seem not occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all()  only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all()  on the pure PHP code.

3 : Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function :

The code at end this post :

This function not support :
- Old notation :  "<?  ?>" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)
Dennis Robinson from basnetworks dot net
8 years ago
I wanted to use the tokenizer functions to count source lines of code, including counting comments.  Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations.  The token_get_all() function makes this task easy by detecting all the comments properly.  However, it does not tokenize newline characters.  I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.


('T_NEW_LINE', -1);

$new_tokens = array();

// Get the tokens
$tokens = token_get_all($source);

// Split newlines into their own tokens
foreach ($tokens as $token)
$token_name = is_array($token) ? $token[0] : null;
$token_data = is_array($token) ? $token[1] : $token;

// Do not split encapsed strings or multiline comments
if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr($token_data, 0, 2) == '/*')
$new_tokens[] = array($token_name, $token_data);

// Split the data up by newlines
$split_data = preg_split('#(\r\n|\n)#', $token_data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        foreach (
$split_data as $data)
            if (
$data == "\r\n" || $data == "\n")
// This is a new line token
$new_tokens[] = array(T_NEW_LINE, $data);
// Add the token under the original token name
$new_tokens[] = is_array($token) ? array($token_name, $data) : $data;


    if (
$token === T_NEW_LINE)



Example usage:


= token_get_all_nl(file_get_contents('somecode.php'));

foreach (
$tokens as $token)
    if (
        echo (
token_name_nl($token[0]) . ': "' . $token[1] . '"<br />');
        echo (
'"' . $token . '"<br />');


I'm sure you can figure out how to count the lines of code, and lines of comments with these functions.  This was a huge improvement on my previous attempt at counting lines of code with regular expressions.  I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.
1 year ago
The T_OPEN_TAG token will include the first trailing newline (\r, \n, or \r\n), tab (\t), or space. Any additional space after this token will be in a T_WHITESPACE token.

The T_CLOSE_TAG token will include the first trailing newline (\r, \n, or \r\n; as described here http://php.net/manual/en/language.basic-syntax.instruction-separation.php). Any additional space after this token will be in a T_INLINE_HTML token.
8 months ago
Not all tokens are returned as an array. The rule appears to be that if a token is not variable, but instead it is one particular constant string, it is returned as a string instead. You don't get a line number. This is the case for braces( "{", "}"), parentheses ("(", ")"), brackets ("[", "]"), comma (","), semi-colon (";"), and a whole slew of operator signs ("!", "=", "+", "*", "/", ".", "+=", ...).
kevin at metalaxe dot com
9 years ago
Rogier, thanks for that fix. This bug still exists in php 5.2.5. I did notice though that it is possible for a notice to pop up from your code. Changing this line:

            $temp[] = $tokens[0][2];

To read this:

            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

fixes this notice.
10 years ago
Complementary note to code below:
Note that only the FIRST 2 (or 3, if needed) array elements will be updated.

Since I only encountered incorrect results on the FIRST occurence of T_OPEN_TAG, I wrote this quick fix.
Any other following T_OPEN_TAG are, on my testing system (Apache 2.0.52, PHP 5.0.3), parsed correctly.

So, This function assumes only a possibly incorrect first T_OPEN_TAG.
Also, this function assumes the very first element (and ONLY the first element) of the token array to be the possibly incorrect token.
This effectively translates to the first character of the tokenized source to be the start of a php script opening tag '<', followed by either 'php' OR '%' (ASP_style)
To Top