token_get_all

token_get_all(string $code, int $flags = 0): array

Source tokenization: token_get_all splits PHP source into a token stream (T_ECHO/T_VARIABLE, etc.) using the Zend engine lexical scanner — the foundation of static analysis and code tooling.

C C23

C23
#include <ctype.h>
#include <stdio.h>

int main(void) {
    /* C has no standard tokenizer: a tiny hand-rolled lexer for the demo
       (production tools build on compiler front ends such as libclang) */
    const char *code = "int greet = 42;";
    char buf[64];
    int n = 0, count = 0;
    for (const char *p = code; *p; p++) {
        if (isspace((unsigned char)*p)) {
            continue;
        }
        if (isalpha((unsigned char)*p) || *p == '_') {
            n = 0;
            while (isalnum((unsigned char)*p) || *p == '_') buf[n++] = *p++;
            buf[n] = '\0';
            p--;
            printf("%s ", buf);
        } else if (isdigit((unsigned char)*p)) {
            n = 0;
            while (isdigit((unsigned char)*p)) buf[n++] = *p++;
            buf[n] = '\0';
            p--;
            printf("%s ", buf);
        } else {
            printf("%c ", *p);
        }
        count++;
    }
    printf("\ncount: %d\n", count);
    return 0;
}
Output
int greet = 42 ; 
count: 5

C++ C++26

C++26
#include <iostream>
#include <regex>
#include <string>
#include <vector>

int main() {
    // C++ has no standard tokenizer: std::regex splitting stands in for the demo
    std::string code = "int greet = 42;";
    std::regex re(R"([A-Za-z_]\w*|\d+|\S)");
    std::vector<std::string> tokens;
    for (std::sregex_iterator it(code.begin(), code.end(), re), end; it != end; ++it) {
        tokens.push_back(it->str());
    }
    for (size_t i = 0; i < tokens.size(); i++) {
        std::cout << tokens[i] << (i + 1 < tokens.size() ? " " : "\n");
    }
    std::cout << "count: " << tokens.size() << "\n";
    return 0;
}
Output
int greet = 42 ;
count: 5

C# v11.0.100

v11.0.100
// No standard tokenizer in the BCL: a hand-rolled regex splitter stands in
string code = "int greet = 42;";
var tokens = System.Text.RegularExpressions.Regex
    .Matches(code, "[A-Za-z_]\\w*|\\d+|\\S")
    .Select(m => m.Value)
    .ToList();
Console.WriteLine(string.Join(" ", tokens));
Console.WriteLine($"count: {tokens.Count}");
Output
int greet = 42 ;
count: 5

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"go/scanner"
	"go/token"
)

func main() {
	// go/token + go/scanner are the standard library's tokenizer
	src := []byte("package main\nvar greet = \"Hello\"\n")
	var s scanner.Scanner
	fs := token.NewFileSet()
	f := fs.AddFile("demo.go", fs.Base(), len(src))
	s.Init(f, src, nil, 0)
	count := 0
	for {
		_, tok, lit := s.Scan()
		if tok == token.EOF {
			break
		}
		fmt.Printf("%s ", tok.String())
		if lit != "" {
			fmt.Printf("(%q) ", lit)
		}
		count++
	}
	fmt.Printf("\ncount: %d\n", count)
}
Output
package ("package") IDENT ("main") ; ("\n") var ("var") IDENT ("greet") = STRING ("\"Hello\"") ; ("\n") 
count: 8

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        // No simple standard tokenizer API: a hand-rolled regex splitter stands in
        // (the javax.tools.JavaCompiler API is the heavyweight official route)
        String code = "int greet = 42;";
        java.util.regex.Matcher m = java.util.regex.Pattern
            .compile("[A-Za-z_]\\w*|\\d+|\\S").matcher(code);
        java.util.List<String> tokens = new java.util.ArrayList<>();
        while (m.find()) {
            tokens.add(m.group());
        }
        System.out.println(String.join(" ", tokens));
        System.out.println("count: " + tokens.size());
    }
}
Output
int greet = 42 ;
count: 5

JavaScript v26.13.1

v26.13.1
// No standard tokenizer: a hand-rolled regex splitter stands in for the demo
const code = 'const greet = "Hello";';
const tokens = code.match(/"[^"]*"|'[^']*'|[A-Za-z_]\w*|\d+|\S/g) ?? [];
console.log(tokens.join(" "));
console.log("count:", tokens.length);
Output
const greet = "Hello" ;
count: 5

PHP v8.6.0

v8.6.0
// token_get_all splits source into Zend-engine lexical tokens
$tokens = token_get_all('<?php echo $greet . "!";');
$names = [];
foreach ($tokens as $t) {
    $names[] = is_array($t) ? token_name($t[0]) : $t;
}
echo implode(" ", $names), "\n";
echo "count: ", count($tokens), "\n";
Output
T_OPEN_TAG T_ECHO T_WHITESPACE T_VARIABLE T_WHITESPACE . T_WHITESPACE T_CONSTANT_ENCAPSED_STRING ;
count: 9

Python v3.15.2

v3.15.2
# The stdlib tokenize module splits source into lexical tokens
import io
import tokenize

code = 'greet = "Hello"\nprint(greet)\n'
names = [tokenize.tok_name[tok.type] for tok in tokenize.generate_tokens(io.StringIO(code).readline)]
print(" ".join(names))
print("count:", len(names))
Output
NAME OP STRING NEWLINE NAME OP NAME OP NEWLINE ENDMARKER
count: 10

Rust v1.99.1

v1.99.1
fn main() {
    // No stable public tokenizer in std: a hand-rolled splitter stands in for the demo
    let code = "let greet = 42;";
    let mut tokens: Vec<String> = Vec::new();
    let mut chars = code.char_indices().peekable();
    while let Some((i, c)) = chars.next() {
        if c.is_whitespace() {
            continue;
        }
        if c.is_alphanumeric() || c == '_' {
            let start = i;
            let mut end = code.len();
            while let Some(&(j, c2)) = chars.peek() {
                if c2.is_alphanumeric() || c2 == '_' {
                    chars.next();
                } else {
                    end = j;
                    break;
                }
            }
            tokens.push(code[start..end].to_string());
        } else {
            tokens.push(c.to_string());
        }
    }
    println!("{}", tokens.join(" "));
    println!("count: {}", tokens.len());
}
Output
let greet = 42 ;
count: 5

TypeScript v26.13.1

v26.13.1
// No standard tokenizer: a hand-rolled regex splitter stands in for the demo
const code: string = 'const greet = "Hello";';
const tokens: RegExpMatchArray = code.match(/"[^"]*"|'[^']*'|[A-Za-z_]\w*|\d+|\S/g) ?? [];
console.log(tokens.join(" "));
console.log("count:", tokens.length);
Output
const greet = "Hello" ;
count: 5

Language differences

PHP: token_get_all splits source with the Zend engine lexical scanner — named tokens come as [id, text, line] triples while single-character tokens come back as plain strings; the TOKEN_PARSE flag recognizes reserved words in specific contexts; the OOP counterpart is PhpToken::tokenize() (PHP 8.0+).

Python: the tokenize standard library is the one-to-one counterpart (generate_tokens yields named tokens, tok_name maps type codes to names).

Go: go/token + go/scanner are the standard-library tokenizer — the scanner performs automatic semicolon insertion (the ; ("\n") in the output is an inserted semicolon).

Rust: proc_macro's TokenStream only serves macros, not general source tokenization (no public general lexer on stable); the demo hand-rolls a minimal splitter.

Java: javax.tools.JavaCompiler is the heavyweight official route; the demo uses a hand-rolled regex.

C/C++: no standard tokenizer — production tools build on compiler front ends (libclang); the demo is minimal hand-rolled.

JavaScript/TypeScript: no standard — acorn/esprima are the ecosystem standards; the demo uses a hand-rolled regex.

C#: no standard tokenizer in the BCL — Roslyn (Microsoft.CodeAnalysis) is the production-grade solution; the demo uses a hand-rolled regex.