<?php
use Doctrine\Common\Lexer\AbstractLexer;
class MathLexer extends AbstractLexer
{
/**
* better: a token for every operator
* instead of T_OPERATOR
*/
const T_OPERATOR = 1;
const T_FORMULA = 2;
/**
* Lexical catchable patterns.
*
* @return array
*/
protected function getCatchablePatterns()
{
return array(
'[\+\-\/\*]+',
'[a-zA-Z]+',
);
}
/**
* Lexical non-catchable patterns.
*
* @return array
*/
protected function getNonCatchablePatterns()
{
return array(
'\s+',
);
}
/**
* Retrieve token type.
*
* @param string $value
*
* @return integer
*/
protected function getType(&$value)
{
if (preg_match('/[\+\-\/\*]+/', $value)) {
return self::T_OPERATOR;
}
return self::T_FORMULA;
}
}
$lexer = new MathLexer();
$lexer->setInput('X + Y - Z');
$lexer->moveNext();
while(null !== $lexer->lookahead) {
// lookahead is an array with token elements
// value: value of token
// position: position in initial string
// type: integer (see constants)
echo '"' . $lexer->lookahead['value'] . '"';
echo ' is of type ' . $lexer->lookahead['type'] . PHP_EOL;
$lexer->moveNext();
}