Import laravel_rust_format_core::php for PHP core behavior. Use str for Laravel’s Unicode string helpers and number for Laravel’s English number helpers.
Free-form dates
strtotime(text, now, &zone) returns Unix seconds. date_create(text, &zone, now)
returns a Jiff zoned date-time and keeps microseconds. An invalid expression returns
None, the Rust representation of PHP's false. An explicit zone in the expression
overrides the output zone. Both functions require a clock.
use jiff::{Timestamp, tz::TimeZone};
use laravel_rust_format_core::{carbon, php};
let base = Timestamp::UNIX_EPOCH;
assert_eq!(php::strtotime("+1 week", base, &TimeZone::UTC), Some(604800));
assert_eq!(php::strtotime("unknown date?", base, &TimeZone::UTC), None);
let date = php::date_create("2024-02-30 24:00 GMT+2", &TimeZone::UTC, base).unwrap();
assert_eq!(carbon::format(date, "Y-m-d H:i P").unwrap(), "2024-03-02 00:00 +02:00");Rounding and printing
use laravel_rust_format_core::php;
assert_eq!(php::number_format(1.005, 2).unwrap(), "1.01");
assert_eq!(php::number_format(1234.5, -2).unwrap(), "1,200");
assert_eq!(php::number_format_with(1234.5, 2, ",", "\u{202f}").unwrap(), "1\u{202f}234,50");
assert_eq!(php::round(1.005, 2), 1.01);
assert_eq!(php::round_with(1250, -2, php::RoundingMode::HalfOdd), 1300.0);
let mode = php::RoundingMode::try_from(php::PHP_ROUND_HALF_EVEN).unwrap();
assert_eq!(php::round_with(1250, -2, mode), 1200.0);
assert_eq!(php::round(-0.4, 0).to_bits(), (-0.0_f64).to_bits());
assert_eq!(php::echo(0.1 + 0.2), "0.3");
assert_eq!(php::echo(1e14), "1.0E+14");| PHP call | Rust API | Return and behavior |
|---|---|---|
number_format($n, $decimals) | php::number_format(n, decimals) | Result<String>. Ties round away from zero. Negative precision rounds to the left of the decimal point. |
number_format($n, $decimals, $point, $sep) | php::number_format_with(n, decimals, point, sep) | Result<String>. Separators are inserted literally and may be empty. |
round($n, $precision) | php::round(n, precision) | f64, with PHP’s default half-away-from-zero mode. |
round($n, $precision, $mode) | php::round_with(n, precision, mode) | f64, with any PHP 8.4 RoundingMode. Convert legacy integer modes with RoundingMode::try_from. |
echo $n, (string) $n | php::echo(n) | String. Floats use PHP’s default precision=14, including its exponent spelling and signed zero. Integers keep their digits. |
For a Blade expression that printed a rounded number, compose php::echo(php::round(n, precision)). Keep the f64 from round when you need to do more arithmetic.
ASCII case
use laravel_rust_format_core::{php, str};
assert_eq!(php::ucfirst("élan"), "élan");
assert_eq!(str::ucfirst("élan"), "Élan");
assert_eq!(php::lcfirst("HELLO"), "hELLO");
assert_eq!(php::ucwords("one-two\tthree"), "One-two\tThree");
assert_eq!(php::ucwords_with("one-two three", "-"), "One-Two three");
assert_eq!(php::strtolower("CAFÉ"), "cafÉ");
assert_eq!(php::strtoupper("café"), "CAFé");
ucfirst and lcfirst act on the initial ASCII letter. ucwords also acts after whitespace delimiters. Pass custom delimiter bytes or ranges such as 0..9 to ucwords_with. strtolower and strtoupper act throughout the string. All five preserve non-ASCII UTF-8 bytes.
PHP values in migrated templates
Use Rust semantics for new code. The helpers here preserve PHP behavior where an existing template depends on PHP’s output, casts or comparisons.
| PHP call or expression | Rust API | Behavior |
|---|---|---|
echo $value, (string) $value | php::echo(&value), php::strval(&value) | False and null give an empty string, true gives "1", and an array gives "Array". PHP also warns on array-to-string conversion. |
(bool) $value | php::boolval(&value) | The only false strings are "" and "0". An empty array is false. NaN is true. |
$left == $right | php::loose_eq(&left, &right) | Numeric strings compare numerically. A boolean operand triggers truth conversion. Two arrays compare recursively by key, independent of order. |
(int) $value | php::intval(&value) | Reads a decimal prefix from strings, including exponents. Finite string overflows saturate. Floats truncate toward zero and wrap modulo 2⁶⁴. NaN and infinity give zero. |
(float) $value | php::floatval(&value) | Reads a decimal prefix and preserves signed zero. Numeric casts of arrays give zero for an empty array and one otherwise. |
array_filter($array) | php::array_filter(&array)? | Keeps original keys and order, dropping values that PHP considers false. |
array_values($array) | php::array_values(&array)? | Returns the values in order with keys renumbered from zero. |
PhpValue and PhpArray are owned. Insert PhpKey::Int or PhpKey::String into a PhpArray. Canonical decimal integer keys such as "1" and "-5" become integers. Keys such as "01", "1.0", " 1" and "-0" remain strings. Replacing a key keeps its position. The next append starts at zero when there is no integer key and otherwise follows the greatest integer key, including a negative one.
use laravel_rust_format_core::php::{self, JsonFlags, PhpArray, PhpValue};
let mut array = PhpArray::default();
array.append(PhpValue::String("0".into())).unwrap();
array.append(PhpValue::String("00".into())).unwrap();
let retained = php::array_filter(&array).unwrap();
assert_eq!(php::json_encode(&retained, JsonFlags::NONE).unwrap(), r#"{"1":"00"}"#);
assert_eq!(php::json_encode(&php::array_values(&retained).unwrap(), JsonFlags::NONE).unwrap(), r#"["00"]"#);
assert!(php::loose_eq("01", "1"));
assert!(!php::loose_eq("abc", &0));
assert_eq!(php::intval(" 12abc"), 12);
A host engine can implement AsPhpValue for its own enum. kind() borrows string data and reports array length, and entries() yields normalized keys and borrowed elements in order. The helpers use static dispatch, so they can traverse the host’s values directly. A helper returning an owned array copies the selected contents into that array.
Enable the core crate’s serde_json Cargo feature to use serde_json::Value directly or convert with PhpValue::from(&value). JSON arrays become PHP lists, and JSON objects become PHP arrays with normalized keys. Unsigned integers outside the signed 64-bit range become floats. JSON object order follows the caller’s choice of serde_json/preserve_order.
Existing primitive numeric calls such as php::echo(0.1 + 0.2) still work. With a custom type previously accepted through Into<PhpNumber>, first convert it with let number: PhpNumber = value.into(), then call php::echo(number).
A custom view enum can expose nested lists and borrowed text without constructing a separate PHP array or copying the strings. Its Element type is Self so lists can contain more lists.
use laravel_rust_format_core::php::{AsPhpValue, JsonFlags, PhpKeyRef, PhpKind, json_encode};
enum Input<'a> {
Text(&'a str),
Number(i64),
List(&'a [Input<'a>]),
}
impl AsPhpValue for Input<'_> {
type Element = Self;
fn kind(&self) -> PhpKind<'_> {
match self {
Self::Text(text) => PhpKind::String(text),
Self::Number(number) => PhpKind::Int(*number),
Self::List(items) => PhpKind::Array(items.len()),
}
}
fn entries(&self) -> impl Iterator<Item = (PhpKeyRef<'_>, &Self)> {
let items = match self {
Self::List(items) => *items,
_ => &[],
};
items.iter().enumerate().map(|(index, item)| (PhpKeyRef::Int(index as i64), item))
}
}
let description = String::from("Café");
let details = [Input::Text(&description), Input::Number(7)];
let row = [Input::Text("row"), Input::List(&details)];
assert_eq!(
json_encode(&Input::List(&row), JsonFlags::UNESCAPED_UNICODE).unwrap(),
r#"["row",["Café",7]]"#
);Joining Laravel arrays and collections
Use arr::join(&items, glue) for the default final glue or arr::join_with(&items, glue, final_glue)
to set it. A singleton with a nonempty final glue returns its original value, including its type.
use laravel_rust_format_core::{arr, php::{PhpArray, PhpValue}};
let mut items = PhpArray::default();
items.append(PhpValue::Int(12)).unwrap();
assert_eq!(arr::join_with(&items, ", ", " and ").unwrap(), PhpValue::Int(12));
items.append(PhpValue::String("café".into())).unwrap();
assert_eq!(arr::join(&items, ", ").unwrap(), "12, café");
assert_eq!(arr::join_with(&items, ", ", " and ").unwrap(), PhpValue::String("12 and café".into()));
arr::collection_join and arr::collection_join_with follow Laravel’s collection rules. If the
first item is an array, the glue selects a field path for the prefix instead of delimiting it.
Formatted strings
php::sprintf(format, &args) supports %b %c %d %e %E %f %F %g %G %h %H %o %s %u %x %X %% using the C locale. It accepts argument numbers such as %2$s, padding and alignment flags, width, precision and integer width or precision arguments such as %3$*1$.*2$f. Invalid formats and non-integer dynamic widths or precisions return ErrorKind::InvalidArgument. Too few arguments return ErrorKind::ArgumentCountError.
use laravel_rust_format_core::php::{sprintf, PhpValue};
let args = [PhpValue::Int(7), PhpValue::Int(2), PhpValue::Float(1.005)];
assert_eq!(sprintf("%3$*1$.*2$f", &args).unwrap(), " 1.00");
assert_eq!(sprintf("%.0e", &[2.5]).unwrap(), "2e+0");
Float rounding in sprintf uses the stored float, with ties to even. Scientific exponents have an explicit sign and no leading zeros. PHP allows precision -1 through * with %g %G %h %H for the shortest round-tripping form. For a bare precision dot on a floating-point conversion, the helper follows PHP 8.4 and uses the default precision. Write .0 for the zero precision PHP 8.5 uses there.
Widths and string precision are measured in bytes. Use php::sprintf_bytes to reproduce byte output such as %c with 255 or %.1s with "é". php::sprintf returns ErrorKind::Unsupported when the output would be invalid UTF-8.
Use php::printf and php::vprintf to write to a std::fmt::Write and return the byte count.
vprintf accepts a PHP array view and uses its insertion order. php::fprintf accepts an
std::io::Write and can write arbitrary bytes. All three validate the formatted output before writing.
use laravel_rust_format_core::php::{fprintf, printf};
let mut text = String::new();
assert_eq!(printf(&mut text, "%s!", &["café"]).unwrap(), 6);
assert_eq!(text, "café!");
let mut bytes = Vec::new();
assert_eq!(fprintf(&mut bytes, "%c", &[255]).unwrap(), 1);
assert_eq!(bytes, [0xff]);JSON and JavaScript for Blade
php::json_encode(&value, JsonFlags::BLADE) uses Blade’s four HEX flags at depth 512. php::json_encode_with(&value, flags, depth) exposes PHP’s depth and flag arguments. Combine flags with | or pass the PHP mask through JsonFlags::from_bits.
php::json_encode_bytes(bytes, flags) encodes a PHP string with arbitrary bytes.
INVALID_UTF8_IGNORE takes precedence over INVALID_UTF8_SUBSTITUTE when both are set.
Without either, malformed input returns a JSON error or produces null under PARTIAL_OUTPUT_ON_ERROR.
use laravel_rust_format_core::php::{JsonFlags, json_encode_bytes};
assert_eq!(json_encode_bytes(b"a\xffb", JsonFlags::INVALID_UTF8_SUBSTITUTE).unwrap(), r#""a\ufffdb""#);use laravel_rust_format_core::{js, php::{JsonFlags, PhpArray, PhpValue, json_encode_with}};
assert_eq!(json_encode_with("01", JsonFlags::NUMERIC_CHECK, 1).unwrap(), "1");
let mut list = PhpArray::default();
list.append(PhpValue::Int(1)).unwrap();
list.append(PhpValue::Int(2)).unwrap();
assert_eq!(js::from(&list, JsonFlags::NONE, 512).unwrap(), "JSON.parse('[1,2]')");
The encoder uses PHP’s default serialize_precision=-1. Array keys 0, 1, … in that order give a list. Other arrays are encoded as objects, and FORCE_OBJECT also encodes lists as objects. For object values backed by a custom AsPhpValue array view, implement is_json_object to preserve the object shape, even for empty objects or objects with numeric property names. PARTIAL_OUTPUT_ON_ERROR writes zero for NaN or infinity, null for recursive members, and keeps output beyond the requested depth. Other encoding failures return ErrorKind::JsonException, with or without THROW_ON_ERROR. Both PHP invalid-UTF-8 options are accepted and have no effect on Rust strings.
js::from follows Illuminate\Support\Js::from. It adds the required escapes and renders strings as JavaScript string literals. Nonempty lists and objects use JSON.parse, while empty arrays, objects and scalar values render directly. See the template contexts and flag list.
PHP string functions
PHP 8.4 string helpers are available through laravel_rust_format_core::php. The string primitives take borrowed UTF-8. Helpers that take mixed or array operands use AsPhpValue, so a template engine can pass its own borrowed view of the values. The crate provides PhpArray and PhpValue when you need to construct these values in Rust.
use laravel_rust_format_core::php::{
ENT_HTML5, ENT_QUOTES, Pad, e, htmlspecialchars_with, mb_str_pad_with, str_pad_with,
};
assert_eq!(e("<p>&").unwrap(), "<p>&amp;");
assert_eq!(
htmlspecialchars_with("& &bogus; '", ENT_HTML5 | ENT_QUOTES, false),
"& &bogus; '"
);
assert_eq!(str_pad_with("x", 2, "é", Pad::Right).unwrap(), [b'x', 0xc3]);
assert_eq!(mb_str_pad_with("x", 4, "猫犬", Pad::Both).unwrap(), "猫x猫犬");
Byte-oriented calls preserve PHP's output even when it splits a multibyte character. Use the byte result directly when writing to a byte stream, or try std::str::from_utf8 or String::from_utf8 at a UTF-8 boundary. The mb_* calls operate on UTF-8 scalars. mb_strwidth counts combining marks as one column and uses PHP's wide-character ranges.
str_replace and str_ireplace return the result and the replacement count. For multiple search terms, PHP applies each term to the output of the previous one. strtr with a replacement array matches the longest key first and skips rescanning the inserted text. http_build_query walks PHP array entries in insertion order. It drops null values and applies the numeric prefix to top-level integer keys only.
Resource budgets
Use php::Limits to set byte and item ceilings. Its defaults are 8 MiB and 100,000 collection entries. PHP exposes number_format_with_limits, str_pad_with_limits, mb_str_pad_with_limits, str_repeat_with_limits, sprintf_with_limits and sprintf_bytes_with_limits. The byte ceiling includes separators, signs, literals and escapes. PHP’s finite-float sprintf conversions cap precision at 53 places. String precision truncates the borrowed input.
The PHP array helpers below limit traversal to 512 nested arrays. Use php::try_loose_eq if the caller needs the error. The original bool-returning php::loose_eq maps it to false. php::try_owned_value, array_filter, array_values and http_build_query report the same error. Owned PHP values are trees. Custom AsPhpValue implementations can expose reference graphs. Storage identity can short-circuit comparison and the depth check rejects traversals that would keep following a cycle. The serde_json From conversion remains infallible and uses an explicit stack for its acyclic input.
Regular expression splitting
use laravel_rust_format_core::{php::preg_split_with, str::{SplitOptions, SplitPart}};
let options = SplitOptions::default().no_empty(true).offset_capture(true);
assert_eq!(
preg_split_with("/,/", ",é,a", options).unwrap(),
[SplitPart::Offset("é".as_bytes(), 1), SplitPart::Offset(b"a", 4)],
);
preg_split returns byte slices because PHP's regex can split a UTF-8 scalar.
Offsets count bytes, including in Unicode mode. An unmatched interior capture
has offset -1. Zero and -1 allow unlimited splitting within the regex policy.
Delimiter captures and skipped empty fields do not count toward the split limit.
Community package, not affiliated with Laravel.