Strings

laravel-rust-format Alpha Laravel for Rust

Used in production across multiple projects.

Import laravel_rust_format_core::str for the supported Illuminate\Support\Str helpers.

Fluent strings

use laravel_rust_format_core::str::{of, SplitOptions, SplitPart};

assert_eq!(
    of("  Café Guide ").trim().slug().append(&[".html"]).into_string(),
    "cafe-guide.html",
);
assert_eq!(of("42").pad_left_with(4, "0").unwrap().as_str(), "0042");
assert!(of(" YES ").to_boolean());

let line = of("é, a, b");
assert_eq!(
    line.split_with("/, */u", SplitOptions::default().limit(2).offset_capture(true)).unwrap(),
    [SplitPart::Offset("é", 0), SplitPart::Offset("a, b", 4)],
);
assert_eq!(of("東京都").split_chars(2).unwrap(), ["東京", "都"]);

of accepts borrowed text, an owned String or a Cow<str>. Transformations consume the wrapper. Slicing keeps borrowed text borrowed. Use ? to continue a chain after a fallible call, or pipe to wrap a closure’s text result and continue. when and unless apply an optional transform. Methods that return slices, including explode and split, borrow the wrapper.

split takes a delimited regex, with split_with for the limit and flags. split_chars implements Laravel's integer overload. Use php::preg_split for arbitrary bytes. A prepared Pattern can split many subjects without recompiling.

use laravel_rust_format_core::{php::PhpValue, str::scan};

assert_eq!(
    scan("42 apples", "%d %s %d").unwrap(),
    [PhpValue::Int(42), PhpValue::String("apples".into()), PhpValue::Null],
);

scan also works as a method. Format widths and %n count bytes. Fields left unassigned after a conversion fails are null, or the collection is empty when PHP returns an end-of-input result before any conversion.

Limit text by display width or by words

use laravel_rust_format_core::str::{self, Limit};

assert_eq!(str::limit("東京", 2), "東...");
assert_eq!(str::limit_with("東京は", 4, "…"), "東京…");
assert_eq!(
    Limit::new(8).end("…").preserve_words().apply("<b>Visit Lisbon</b>"),
    "Visit…",
);
assert_eq!(str::words("one, two three", 2), "one, two...");
assert_eq!(str::words_with("Visit Lisbon soon", 2, "…"), "Visit Lisbon…");

limit counts wide and fullwidth scalars as two. Every other scalar counts as one, including combining marks and joiners. The ending is added after truncation, outside the width budget. A fitting input is returned verbatim. On the truncation path, preserve_words() also strips tags, collapses runs of carriage returns and line feeds and tries to keep whole words. Use it for text layout. Apply escaping separately when rendering HTML.

words keeps up to the requested number of whitespace-delimited words. Both helpers default to .... Use the _with form for a different ending. words_with returns the input unchanged for a count of zero or above PCRE’s quantifier limit of 65,535.

Case and headlines

use laravel_rust_format_core::str;

assert_eq!(str::upper("Straße fi"), "STRASSE FI");
assert_eq!(str::lower("ΟΣ ΟΣΑ İ"), "ος οσα i\u{307}");
assert_eq!(str::title("džEMAL 1st"), "Džemal 1St");
assert_eq!(str::ucfirst("élan"), "Élan");
assert_eq!(str::lcfirst("İSTANBUL"), "i\u{307}STANBUL");
assert_eq!(str::ucsplit("aLElan"), ["a", "L", "Elan"]);
assert_eq!(str::headline("emailNotificationSent"), "Email Notification Sent");

title follows mbstring’s title-case rules. ucfirst titlecases the initial scalar and lcfirst lowercases it, each leaving the rest alone. ucsplit returns borrowed slices split before uppercase letters. headline handles whitespace or splits a single word at uppercase boundaries, and recognizes hyphens and underscores.

Transliteration and slugs

use laravel_rust_format_core::str::{self, Slug};

assert_eq!(str::ascii("Ünïcödé Straße"), "Unicode Strasse");
assert_eq!(str::ascii_with("Ärger", "DE-DE"), "Aerger");
assert_eq!(str::slug("Café Mañana & Co."), "cafe-manana-co");
assert_eq!(str::slug_with("São Tomé and Príncipe", "_"), "sao_tome_and_principe");
assert_eq!(
    Slug::new().separator("_").language(None).dictionary([("&", "and")])
        .apply("Café & 北京"),
    "café_and_北京",
);

ascii uses English transliteration tables. Give ascii_with a language code to select another table. slug defaults to English, a hyphen separator and an @ → at dictionary entry. Slug::language(None) skips transliteration, so Unicode letters can survive. A custom dictionary replaces the default dictionary. For slugs used as permanent identifiers, keep the same language, separator and dictionary across deployments.

English inflection

use laravel_rust_format_core::str;

assert_eq!(str::plural("city", 2), "cities");
assert_eq!(str::plural("city", -1.5), "city");
assert_eq!(str::pluralize("octopus"), "octopuses");
assert_eq!(str::singular("CHILDREN"), "CHILD");
assert_eq!(str::plural_studly("blogPost", 2), "blogPosts");
assert_eq!(str::plural_pascal("StepChild", 2), "StepChildren");
assert_eq!(str::plural_with_count("source", 1234), "1,234 sources");

plural follows Laravel’s count rule. It keeps the word as supplied when the absolute integer part of the count is one. Pass a collection’s length explicitly. pluralize supplies the default count of two. Use plural_studly or plural_pascal to inflect the final segment of a compound identifier. Use plural_with_count for PHP’s Str::plural($value, $count, prependCount: true).

See parity for the Unicode and PCRE versions behind these behaviors.

Search, slices and validation

The str module provides Laravel's search, slicing, and validation helpers. Pass a borrowed &str for text and a slice of &str values for an array of needles. The slicing helpers return a borrowed view when the result is part of the original text.

use laravel_rust_format_core::str::{
    after_last, contains_any_with, excerpt_with, is_any, position_with, substr,
    substr_count_with, unwrap_with,
};

assert_eq!(after_last("été / 東京 / 京都", " / "), "京都");
assert!(contains_any_with("CAFÉ", &["tea", "fé"], true));
assert!(is_any(&["admin/*", "docs/*"], "docs/my-page"));
assert_eq!(unwrap_with("[[hello]]", "[", "]"), "[hello]");
assert_eq!(excerpt_with("Long prefix CAFÉ long suffix", "café", 0, "…").as_deref(), Some("…CAFÉ…"));

assert_eq!(position_with("é🙂z", "z", 0, None).unwrap(), Some(2));
assert_eq!(substr("é🙂z", -2), "🙂z");
assert_eq!(substr_count_with("ééx", "é", 1, Some(-1)).unwrap(), 1);

Positions and slices use UTF-8 scalar indices by default. substr_count_with uses byte ranges. To supply an explicit encoding, use length_with, position_with, or substr_encoded. Encoded slices return bytes because PHP may split a UTF-8 scalar when interpreting the string in a single-byte encoding.

String transformations

The str module takes UTF-8 strings and follows Laravel 13's case and string transformations. Use the short calls for PHP defaults and the corresponding _with functions to pass options.

use laravel_rust_format_core::str::{
    CaseMode, Replacements, convert_case_with, mask_with, replace_many,
    snake, studly_with, to_base64, trim, word_wrap_with,
};

assert_eq!(snake("getHTTPResponse"), "get_h_t_t_p_response");
assert_eq!(studly_with("XML_parser", true), "XmlParser");
assert_eq!(convert_case_with("Straße", CaseMode::Fold), "strasse");
assert_eq!(mask_with("a🦋éb", "⭐!", 1, Some(-1)).unwrap(), "a⭐⭐b");
assert_eq!(replace_many(&["a", "b"], Replacements::Each(&["b", "c"]), "aba", true), "ccc");
assert_eq!(trim("\u{feff}hello\u{200b}"), "hello");
assert_eq!(word_wrap_with("猫鳥馬 犬", 2, "|", true).unwrap(), "猫鳥|馬|犬");
assert_eq!(to_base64("é"), "w6k=");

Replacement lists are ordered. Each search term sees the preceding replacements. replace_array handles separate replacements for individual occurrences of one term, while swap selects the longest matching term at each position and emits replacement text directly. For a PHP array of subject strings, apply the scalar function to each value and retain the array's keys in the caller.

Padding, repetition, masking and word wrapping return Result and report output lengths that cannot be allocated.

Default trimming includes Laravel's invisible characters. A supplied charlist uses PHP's byte rules and supports ranges such as a..z. The _with trim functions take byte slices because a charlist can remove part of a UTF-8 encoding. Base64 decoding also returns bytes.

append and prepend mirror Laravel’s fluent string concatenation helpers. Parts retain their argument order and use php::strval, so false and null append no bytes and true appends "1".

use laravel_rust_format_core::{php::PhpValue, str};
assert_eq!(str::append("item ", &[PhpValue::Int(7), PhpValue::Bool(true)]), "item 71");
assert_eq!(str::prepend("end", &["first ", "second "]), "first second end");

Use str::pad_both_with_limits, pad_left_with_limits, pad_right_with_limits and repeat_with_limits with php::Limits to check the output size before allocating.

Regex, Markdown and identifiers

Import the helpers from laravel_rust_format_core::str. Regex support is always available. The default markdown and random features enable the Markdown and identifier APIs, respectively.

The regex helpers accept delimited PHP expressions such as /(\d+)/u. match_first and match_all return capture 1 when Laravel would select it. A miss returns an empty string or empty vector, respectively. is_match accepts a single pattern or a slice and stops on the first match. Replacement references use PHP's syntax, including $1, ${1} and \1. A limit applies separately to each pattern.

use laravel_rust_format_core::str::{is_match, match_first, replace_matches_with_limit};

assert!(is_match(&["/^file:/", "/^https:/i"], "HTTPS://example.org").unwrap());
assert_eq!(match_first(r"/ID-(\d+)/", "ID-42").unwrap(), "42");
assert_eq!(replace_matches_with_limit("/x/", "y", "xxx", 1).unwrap(), "yxx");

markdown renders GFM blocks. inline_markdown renders inline formatting with ordinary block markers left as text. It can still render GFM tables. Configure either renderer with MarkdownOptions::default() and the builder methods html_input, allow_unsafe_links and renderer.soft_break. Like Laravel, the default allows raw HTML with the GFM tag filter applied and allows unsafe link schemes. These helpers render HTML and do not provide a general HTML sanitizer.

use laravel_rust_format_core::str::{inline_markdown, markdown};

assert_eq!(markdown("## Heading\n\n~~old~~"), "<h2>Heading</h2>\n<p><del>old</del></p>\n");
assert_eq!(inline_markdown("# **Hello**\n- ~~old~~"), "# <strong>Hello</strong>\n- <del>old</del>\n");

random(16) produces Laravel's default length. password() includes letters, numbers and symbols, and password_with can enable spaces or choose a different length or set of pools. Pass an explicit jiff::Timestamp to the timestamped ID helpers. Reuse an OS-backed StrGenerator when generating multiple UUIDv7s or ULIDs within the same millisecond. An injected RandomSource or closure controls the entropy for repeatable tests.

use laravel_rust_format_core::str::StrGenerator;

let mut fixture = StrGenerator::new(|bytes: &mut [u8]| { bytes.fill(0); Ok(()) });
assert_eq!(fixture.random(3).unwrap(), "AAA");
assert_eq!(fixture.uuid().unwrap(), "00000000-0000-4000-8000-000000000000");

Regex budgets

Compile a delimited PHP PCRE pattern once with str::Pattern::new. Use Pattern::with_limits to pass a RegexLimits policy. Its defaults allow 16 KiB of pattern text, 8 MiB of subject text, one million PCRE2 match operations per engine call, a depth of 1,000, an 8 MiB match heap and at most 100,000 matches per helper call. Replacement lists share a match count and budget each stage. Pattern directives can lower the engine limits. A replacement callback controls its own allocations. Use str::try_is_with or str::try_is_any_with for fallible wildcard predicates.

Community package, not affiliated with Laravel.