One example is worth one thousands words...
<?php
require_once( __DIR__ . "/../expression.php" );
use function \Kalei\Expression\expression;
$parameters = [
"str_1" => "foo",
"str_2" => "BAR",
"a_int" => 1
];
$expression = "( strlen( substr( str_1 . str_2, 3 ) ) + a_int ) ^ 2"
$result = expression( $expression,
$error, // returned by ref.
$parameters,
$elapsedTime ); // returned by ref. (Β΅secs)
if( $result === null )
{
echo "Error: $error\n";
}
else
{
echo "$result\n"; // ==> 16
}
/* step by step:
( strlen( substr( str_1 . str_2, 3 ) ) + a_int ) ^ 2
( strlen( substr( "foo" . "BAR", 3 ) ) + 1 ) ^ 2
( strlen( substr( "fooBAR, 3 ) ) + 1 ) ^ 2
( strlen( "BAR" ) + 1 ) ^ 2
( 3 + 1 ) ^ 2
( 4 ) ^ 2
4^2 = 16
*/
// side note: I do code in Allman style
Β
Β
FIRST ABONINABLE TEMPORARY README FILE GENERATED WITH DUMB CHATGPH
Β
This library provides a collection of PHP functions for string manipulation, mathematical operations, and encoding/decoding. These functions mirror PHP's native capabilities, offering a simple and powerful way to evaluate expressions dynamically.
- Overview
- Available Functions
- Available Operators
- Operator Behavior and Constraints
- Function Definitions
- Usage
This library aims to simplify the evaluation of complex expressions by exposing a set of PHP functions that handle various tasks such as string manipulation, encoding, and mathematical operations. Each function is implemented to closely follow PHP's native functions.
fact
β Factorial of a numberpow
β Power calculationmax
β Maximum of a list of numbersmin
β Minimum of a list of numbersaverage
/avg
β Calculate the average of a list
length
/len
/strlen
β String lengthstrpos
β Find substring positiontrim
β Trim whitespace from both ends of a stringsubstr
β Extract part of a stringltrim
β Left trimrtrim
β Right trim
bin2hex
β Binary to hexadecimal conversionhex2bin
β Hexadecimal to binary conversionchr
β Get character from ASCII valueord
β Get ASCII value of a characterhtmlentities
β Convert special characters to HTML entities
In addition to the provided functions, the following operators are supported for integer and string manipulation:
+
β Addition-
β Subtraction*
β Multiplication/
β Division-
β Unary minus (negation)!
β Factorial (e.g.,5! = 120
)^
β Exponentiation (e.g.,2^3 = 8
)
.
β String concatenation (e.g.,'Hello' . ' World'
results in'Hello World'
)
- Integer Operators (
+
,-
,*
,/
,^
,!
) return integer results. - Division (
/
) is performed using PHP'sintdiv()
function, ensuring the result is always an integer (floor division).intdiv(7, 2); // Returns 3 (not 3.5)
- Results of all integer operations must fit within a 64-bit signed integer.
- Overflowing results will trigger an error.
- Example:
pow(2, 63)
exceeds the 64-bit limit and will result in an error.
String Operator (.
) performs string concatenation and returns a string. There are no overflow limits for string operations.
function fact(int $n): int {{
if ($n < 0) {{
throw new InvalidArgumentException("Factorial is not defined for negative numbers.");
}}
if ($n === 0 || $n === 1) {{
return 1;
}}
$result = 1;
for ($i = 2; $i <= $n; $i++) {{
$result *= $i;
}}
return $result;
}}
function pow(float $base, float $exponent): float {{
return $base ** $exponent;
}}
function max(float ...$values): float {{
if (empty($values)) {{
throw new InvalidArgumentException("At least one value is required.");
}}
return max($values);
}}
function min(float ...$values): float {{
if (empty($values)) {{
throw new InvalidArgumentException("At least one value is required.");
}}
return min($values);
}}
function average(array $values): float {{
if (empty($values)) {{
throw new InvalidArgumentException("Array cannot be empty.");
}}
return array_sum($values) / count($values);
}}
function length(string $str): int {{
return strlen($str);
}}
function strpos(string $haystack, string $needle, int $offset = 0): int {{
$pos = strpos($haystack, $needle, $offset);
return ($pos !== false) ? $pos : -1;
}}
function trim(string $str, string $characters = " \\t\\n\\r\\0\\x0B"): string {{
return trim($str, $characters);
}}
- Import the PHP file into your project.
- Call the functions directly, or invoke them through dynamic expression parsing.
- Combine them to perform complex string manipulations and mathematical evaluations.
We'd love your help in making *expressionPHP better! π
- Report bugs β Let us know if something isnβt working.
- Request features β Have an idea? Weβd love to hear it!
- Fix issues β Check out the open issues and help solve them.
- Improve documentation β Spot a typo or something unclear? PRs welcome!
- Extend the project β Implement new functions (also add tests please)
- Fork the repository (top-right of this page).
- Clone your fork:
git clone https://github.com/your-username/project-name.git
- Create a new branch for your feature or fix:
git checkout -b feature/your-feature
- Make changes and commit:
git commit -m "Add your feature"
- Push to your fork and submit a Pull Request:
git push origin feature/your-feature
- Check out the Issues tab for tasks labeled
good first issue
orhelp wanted
. - Join discussions in the Discussions tab or open a new thread.
C.E.O. and Full Stack Developer at Kalei S.r.l. (based in Italy)
I help commercial businesses reduce costs and improve service levels by facilitating access to product information.
Iβm an entrepreneur and software developer.
When Iβm not working => dad β€οΈ freeclimber π§ββοΈ freediver π π₯½
Copyright (c) 2024-2025 Paolo Bertani - Kalei S.r.l.
Licensed under the FreeBSD 2-clause license
-------------------------------------------------------------------------------
FreeBSD 2-clause license
Copyright (c) 2024-2025, Paolo Bertani - Kalei S.r.l.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \AS IS\ AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------