downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

token_get_all> <tidyNode->isText
[edit] Last updated: Mon, 01 Nov 2010

view this page in

CLIX. Funções de Tokenizer

Introdução

As funções de tokenizer formam uma interface para o tokenizer do PHP imbutido no Engine Zend. Usando essas funções você pode escrever ferramentas próprias para análise e modificação de código PHP sem ter que lidar com a especificação da linguagem em um nível léxico.

Veja também o apêndice sobre tokens.

Dependências

Nenhuma biblioteca externa é necessária para compilar esta extensão.

Instalação

Começando no PHP 4.3.0, essas funções estão habilitadas a menos que seja dito o contrário. Para versões anteriores, você tem que configurar e compilar o PHP com --enable-tokenizer. Você pode desabilitar suporte à extensão tokenizer com --disable-tokenizer.

A versão para Windows do PHP tem suporte embutido para esta extensão. Você não precisa carregar nenhuma extensão adicional para utilizar essas funções.

Nota: Suporte integrado para tokenizer está disponível a partir do PHP 4.3.0.

Constantes pré-definidas

Quando a extensão for ou compilado no PHP ou carregada dinamicamente em tempo de execução, os tokens listados em Apêndice Q são definidos como constantes.

Exemplos

Aqui está um exemplo simples de scripts PHP usando o tokenizer que lerá um arquivo PHP, retirará todos os comentários do fonte e imprimirá apenas o código puro.

Exemplo 1. Retira os comentários com o tokenizer

<?php
/*
 * T_ML_COMMENT não existe no PHP 5.
 * As três linhas seguintes definem ela para
 * preservar compatibilidade com versões anteriores.
 *
 * As duas linhas seguintes definem T_DOC_COMMENT que existe apenas no PHP 5,
 * que nós chamaremos como T_ML_COMMENT para o PHP 4.
 */
if (!defined('T_ML_COMMENT')) {
   
define('T_ML_COMMENT', T_COMMENT);
} else {
   
define('T_DOC_COMMENT', T_ML_COMMENT);
}

$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach (
$tokens as $token) {
    if (
is_string($token)) {
       
// token simples de 1 caracter
       
echo $token;
    } else {
       
// array de tokens
       
list($id, $text) = $token;

        switch (
$id) {
            case
T_COMMENT:
            case
T_ML_COMMENT: // Nós definimos essa
           
case T_DOC_COMMENT: // e essa
                // não faz nada com os comentários
               
break;

            default:
               
// Qualquer outra coisa, imprime como é
               
echo $text;
                break;
        }
    }
}
?>
Índice
token_get_all -- Divide um dado fonte em tokens do PHP
token_name -- Pega o nome simbólico de um dado token do PHP


add a note add a note User Contributed Notes Funções de Tokenizer
lists at 5etdemi dot com 23-Jul-2005 01:33
The tokenizer functions are quite powerful. For example, you can retrieve all of the methods in a given class using an algorithm like:

for each token:
if token is T_FUNCTION then start buffer
if buffer is started then add the current string to the buffer
if token is ( stop buffer

And the great thing is that the class methods will have the right case, so it's a good way to get around the limitations with get_class_methods returning lowercase method names. Also since using a similar algorithm you can read the arguments of a function you can implement Reflections-like functionality into PHP4.

Finally you can use it as a simpler method of extracting Javadoc out of a class file to generate documentation. The util/MethodTable.php class in AMFPHP (http://www.amfphp.org) uses the tokenizer functions to create a method table with all of the arguments, a description, return type, etc. and from that method table it can generate ActionScript that matches the PHP, but it could also be fitted to generate JavaScript, documentation files, or basically anything you put your mind to. I can also see that this could be the base for a class -> WSDL file generator.

 
show source | credits | sitemap | contact | advertising | mirror sites