Expression.php allows for secure evaluation of mathematical, string, and boolean expressions from untrusted sources. With support for custom variables, functions, and various operations, users can safely process complex expressions without compromising security.
Expression.php: A Secure Solution for Evaluating Expressions
Expression.php is a robust library designed for the safe evaluation of mathematical, string, and boolean expressions from untrusted sources. This library provides developers the flexibility to define custom variables and functions, ensuring controlled and secure expression evaluation.
Key Features
- Support for Numeric Types: Handles integers and floating-point numbers efficiently.
- Comprehensive Math Operations: Evaluate expressions using operators such as
*,/,-,+,%,^, and**. - Boolean Logic: Support for boolean expressions with operators like
&&,||, and!. - Comparison Operations: Allows various comparison operators including
>,<,==,!=,<=, and>=. Strict comparisons can also be performed using===and!==. - Built-In Constants: Includes mathematical constants such as
piande. - String Literals and Regular Expressions: Evaluate string content and utilize match operators with regular expressions.
- Complex Data Structures: Work with JSON objects and arrays, including the ability to perform operations using square brackets.
- Bitwise Operations: Engage with bit shift operators
>>and<<. - Custom Functionality: Define and manage user functions and variables effortlessly.
Getting Started
To explore the capabilities of Expression.php, visit the Online REPL for interactive testing. For practical usage, refer to the following PHP code snippet:
require_once(__DIR__ . "/vendor/autoload.php");
use jcubic\Expression;
$e = new Expression();
// Evaluate a simple expression:
$result = $e->evaluate('2+2');
// Advanced expression handling:
$result = $e->evaluate('-8(5/2)^2*(1-sqrt(4))-8');
// Boolean expressions:
$result = $e->evaluate('10 < 20 || 20 > 30 && 10 == 10');
// String and regex evaluations:
$result = $e->evaluate('"Foo,Bar" =~ /^([fo]+),(bar)$/i');
// Custom variables and functions:
$e->evaluate('a = e^(ln(pi))');
$e->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1');
Additional Methods
Expression.php provides various methods to enhance the evaluation process:
evaluate($expr): Evaluates the provided expression and returns the result, printing a warning in case of an error.vars(): Retrieves an associative array of all user-defined variables.funcs(): Returns an array of user-defined functions.
This library originated as a fork and has since undergone significant enhancements to improve its functionality. With a focus on parsing expression grammars, Expression.php offers an efficient and flexible solution for expression evaluation.
Explore more about Expression.php and its functionalities in the GitHub repository.
No comments yet.
Sign in to be the first to comment.