Index

MMO\core\strings

MMO\core\strings · 50 symbols · generated 5 Oct 2026

function

asciiNumber

strings.php:1663

Render a number as large, multi-line ASCII-art digits (ASCII_NUMBERS), for banner-style CLI output (e.g. an HTTP error page/response -- Application::createErrorResponse()).

function asciiNumber(int $num, int $leadingZeros = 0): string
Namespace
MMO\core\strings
$numintthe number to print
$leadingZeros = 0intpad $num with this many leading zeros before rendering
returnsstringa multi-line string
asciiNumber(5); // a 6-line ASCII-art rendering of the digit '5'
Call graph
function

baseConvert

strings.php:141

Convert a number from one base/alphabet to another. A base given as an int uses the first N characters of 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ (so e.g. 16 = hex); a base given as a string uses that string as its own alphabet, position = digit value.

function baseConvert(string|int $number, string|int $to, string|int $from = 10): string
Namespace
MMO\core\strings
$numberstring | intthe number to convert, written in the $from base/alphabet
$tostring | intthe target base (int) or alphabet (string)
$from = 10string | intthe source base (int) or alphabet (string). Default 10 (decimal).
returnsstringthe number represented using the alphabet in $to
baseConvert('123', 16); // '7B' -- decimal 123 in hex (uppercase digits) baseConvert('bcd', 10, 'abcdefghij'); // '123' -- 'a' is 0, 'b' is 1, 'c' is 2, 'd' is 3
function

camelCaseIdentifier

strings.php:69

Convert text to camelCase, treating $separators as word breaks.

function camelCaseIdentifier(string $id, string $separators = ' -'): string
Namespace
MMO\core\strings
The first word is left untouched (lowercase stays lowercase); every subsequent word has its first letter capitalized.
$idstring
$separators = ' -'stringa list of characters to use as word separators
returnsstring
camelCaseIdentifier('first-and-second'); // 'firstAndSecond'
Call graph
function

csvColumnIndex

strings.php:1151

Reverse of csvColumnName(): convert a spreadsheet-style column name back to its 0-based index.

function csvColumnIndex(string $col): int
Namespace
MMO\core\strings
$colstring
returnsint
csvColumnIndex('A'); // 0 csvColumnIndex('AA'); // 26
function

csvColumnName

strings.php:1137

Convert a 0-based column index into a spreadsheet-style column name (A, B, ..., Z, AA, AB, ...).

function csvColumnName(int $index): string
Namespace
MMO\core\strings
$indexint
returnsstring
csvColumnName(0); // 'A' csvColumnName(25); // 'Z' csvColumnName(26); // 'AA'
Call graph
function

csvDecode

strings.php:1016

Decode CSV text into an array of rows.

function csvDecode( string $csv, array|bool $keys = true, string $separator = ';', string $enclosure = '"', string $escape = '\\', ?string $lineSep = MMO\core\strings\PHP_EOL ): array
Namespace
MMO\core\strings
WARNING: if two columns have the same title, data may be overridden -- only one column will be shown in the result.
$csvstringthe csv text
$keys = truearray | boolthe keys to use for each column. - true: use the first line as keys - false: no keys (each row is a plain 0-indexed list) - array: the keys to use directly (every line, including the first, is then data)
$separator = ';'stringthe separator between fields (one single-byte character only)
$enclosure = '"'stringthe field enclosure character (one single-byte character only)
$escape = '\\'stringthe escape character (at most one single-byte character). An empty string ("") disables the proprietary escape mechanism.
$lineSep = MMO\core\strings\PHP_EOLnull | stringthe line separator. If null, the whole $csv is parsed as a single line/row.
returnsarraya list of rows
csvDecode("a;b\n1;2"); // [['a' => '1', 'b' => '2']]
Call graph
function

csvEncode

strings.php:1062

Encode a list of records as CSV text, guessing the headers automatically from the data by default.

function csvEncode( array $data, array|false|null $headers = null, string $sep = ';', string $eol = ' ', ?callable $renderer = null ): string
Namespace
MMO\core\strings
$dataarraya list of maps (key => value). Every record should have the same keys.
$headers = nullarray | false | nullif an array, a map of (key => title) to use as the header row and column order; if null, headers are auto-determined from $data's own keys; if false, no header row is written at all
$sep = ';'stringthe column separator
$eol = ' 'stringthe line separator
$renderer = nullnull | callablea function to convert any value: function(mixed $value, int $line, int $column): mixed
returnsstring
csvEncode([['a' => 1, 'b' => 2], ['a' => 3, 'b' => 4]]); // "a;b\r\n1;2\r\n3;4"csvEncode([['a' => 1, 'b' => 2]], false); // "1;2" -- no header row, but columns still resolved
Call graph
function

csvRawEncode

strings.php:1109

Encode a list of lines as CSV text, without any header handling: each line is either an array of column values (joined with $sep) or an already-formatted raw string (used as-is).

function csvRawEncode( array $lines, string $sep = ';', string $eol = ' ', ?callable $renderer = null ): string
Namespace
MMO\core\strings
$linesarraya list of lines (each an array of values, or a raw string line)
$sep = ';'stringthe column separator
$eol = ' 'stringthe line separator
$renderer = nullnull | callablefunction($value, $line, $column). Only called for array (non-raw-string) lines.
returnsstring
csvRawEncode([['a', 'b'], 'raw line', ['c', 'd']]); // "a;b\r\nraw line\r\nc;d"
function

describe

strings.php:535

Describe any value as a compact, technical/debug string representation (unlike render(), which aims for a human-facing display string): an object uses debugName() if available, else a Class{prop:val,...} dump of its public properties; an array becomes (count){k:v,...} (object-shaped) or (count)[v,...] (list-shaped); true/false/null become 'TRUE'/'FALSE'/'NULL'; nesting stops at $depth, showing (n)[..]/ Class{..} instead of recursing further.

function describe( mixed $val, bool $quoteString = false, int $depth = MMO\core\strings\MMO_DUMP_LEVEL ): string
Namespace
MMO\core\strings
$valmixed
$quoteString = falseboolif true, a string value is quoted and has its own quotes/backslashes/newlines escaped
$depth = MMO\core\strings\MMO_DUMP_LEVELinthow many levels of nested array/object to describe before collapsing to a placeholder
returnsstring
describe(['a' => 1, 'b' => 2]); // '(2){a:1,b:2}' describe([1, 2, 3]); // '(3)[1,2,3]' describe(null); // 'NULL' describe('hi', true); // '"hi"'
Call graph
function

didYouMean

strings.php:1771

The hint an error message adds after an unknown name: the closest known names, so a typo tells its reader (a developer, or an AI agent) what was meant instead of only what was wrong.

function didYouMean(string $value, iterable $choices, int $max = 3): string
Namespace
MMO\core\strings
Case is ignored, and for a class name only its short name is compared (`JsonRepositry` finds `MMO\core\entities\JsonRepository`). A choice counts as close within a third of the name's length, two swapped letters counting as one mistake (`nmae` finds `name`).
$valuestringthe unknown name
$choicesiterablethe names that exist
$max = 3inthow many suggestions at most
returnsstring did you mean [a] or [b]?, with its leading space; '' when nothing is close
didYouMean('peple', ['people', 'items']); // ' did you mean [people]?'didYouMean('nmae', ['name', 'email']); // ' did you mean [name]?'didYouMean('zzz', ['people', 'items']); // ''
Call graph
function

dotIdentifier

strings.php:85

Turn arbitrary text into a lowercase, dot-separated identifier (a common convention for i18n/config keys).

function dotIdentifier(string $id): string
Namespace
MMO\core\strings
$idstring
returnsstring
dotIdentifier('Hello World'); // 'hello.world'
Call graph
function

findMatching

strings.php:313

Find the matching closing delimiter for the first opening delimiter found at/after $offset, correctly handling nesting ({a{b}c}), escaped characters, and quoted sub-sequences (ignored entirely, by default both "..." and '...') that might otherwise contain a stray unmatched delimiter.

function findMatching( string $text, string $open, string $close, int $offset = 0, array $ignoreIn = [['"', '"'], ['\'', '\'']], string $escapeChar = '\\' ): array|false
Namespace
MMO\core\strings
$textstring
$openstringthe opening text to look for
$closestringthe closing text to look for
$offset = 0intthe offset to start searching from
$ignoreIn = [['"', '"'], ['\'', '\'']]arraya list of [start, end] delimiter pairs whose contents are skipped over entirely
$escapeChar = '\\'stringthe char that escapes (skips) the next character
returnsarray | false[start, end] (the opening delimiter's offset, and the offset just AFTER the closing delimiter), or false if no complete, properly matched pair was found
findMatching('a{t}', '{', '}'); // [1, 3]
Call graph
function

findOffset

strings.php:226

Get the character offset for a specific line/column position in a text.

function findOffset( string $text, int $line, int $col = 1, string $eol = MMO\core\strings\PHP_EOL ): int|false
Namespace
MMO\core\strings
$textstring
$lineintthe line number (starting from 1)
$col = 1intthe column number (starting from 1)
$eol = MMO\core\strings\PHP_EOLstringend of line delimiter
returnsint | falsethe offset, or false if $line is beyond the text's last line
findOffset("line1\nline2\nline3", 2, 3); // 8 -- the offset of line 2, column 3 ('n' in "line2")
function

formatFraction

strings.php:190

Format a float as an integer part plus its best rational approximation (a fraction), e.g. for display as a mixed number. Approximates via brute-force search over denominators up to $maxDenominator.

function formatFraction(float $value, int $maxDenominator = 9, string $delimiter = ' + '): string
Namespace
MMO\core\strings
$valuefloat
$maxDenominator = 9intthe maximum denominator to try (9 for tenths, 99 for hundredths, etc.)
$delimiter = ' + 'stringjoins the integer part and the fraction
returnsstring
formatFraction(1.5); // '1 + 1/2' formatFraction(0.5); // '1/2' -- no integer part, delimiter omitted
function

getAccents

strings.php:1484

The accent-folding table stripAccents()/textRegex() are built on: maps every accented Latin character to its plain-letter equivalent (e.g. 'é' -> 'e').

function getAccents(...$chars): array
Namespace
MMO\core\strings
...$chars
returnsarray
getAccents('e')[0]; // 'e' -- and the rest of the returned array holds every accented form of 'e' or 'E'
Call graph
function

getPlaceholders

strings.php:856

Get every placeholder in a template, without rendering/matching anything (a thin wrapper over loopTemplate()).

function getPlaceholders(string $tpl): array
Namespace
MMO\core\strings
$tplstring
returnsarray[path => ['type' => ?string, 'required' => bool, 'offset' => int, 'size' => int]]
getPlaceholders('{a}: {?b:integer}'); // ['a' => ['type'=>null,'required'=>true,'offset'=>0,'size'=>3], 'b' => ['type'=>'integer','required'=>false,'offset'=>5,'size'=>12]]
Call graph
function

hash3

strings.php:1376

Same as hash3Int(), but base-32-encoded (via PHP's own \base_convert(), NOT this file's own baseConvert()) into a short, compact string.

function hash3(string $key, int $seed = 0): string
Namespace
MMO\core\strings
$keystringText to hash.
$seed = 0intPositive integer only
returnsstring
hash3('hello'); // 'i8nui7'
Call graph

Uses (1)

function

hash3Int

strings.php:1364

Compute the MurmurHash3 (32-bit) hash of a string, as an int. A fast, non-cryptographic hash -- good for hash tables/bucketing/deduplication, NOT for security purposes.

function hash3Int(string $key, int $seed = 0): int
Namespace
MMO\core\strings
$keystringText to hash.
$seed = 0intPositive integer only
returnsint32-bit positive integer hash
hash3Int('hello'); // 613153351
Call graph

Uses (1)

Used by (1)

function

hash3Unpack

strings.php:1319

Don't use this function directly unless you know what you are doing.

function hash3Unpack(array $key, int $seed = 0): int
Namespace
MMO\core\strings
Use hash3 or hash3Int instead
$keyarrayan unpack version of a string
$seed = 0intPositive integer only
returnsint32-bit positive integer hash
Call graph

Used by (1)

function

hex

strings.php:420

Convert a string to its hexadecimal representation, one hex number per byte.

function hex(string $str, int $length = 2): string
Namespace
MMO\core\strings
$strstring
$length = 2intthe minimum digit-width of each byte's hex number (zero-padded)
returnsstring
hex('AB'); // '4142'
function

htmlTable

strings.php:1449

Render a list of records (csvEncode()'s $data shape) as a plain HTML <table>, guessing the header row from the data's own keys (in the order first seen).

function htmlTable(array $data, string $title = ''): string
Namespace
MMO\core\strings
NOTE: no escaping is applied to values/headers -- callers passing user-supplied data must escape it themselves.
$dataarraya list of maps (key => value). Every record should have the same keys.
$title = ''stringused as the table's <caption>
returnsstring
htmlTable([['a' => 1, 'b' => 2]], 'Title'); // "<table><caption>Title</caption>\n<thead><tr><th>a</th><th>b</th></tr></thead>\n<tr><td>1</td><td>2</td></tr>\n</table>"
function

indent

strings.php:594

Indent every line of a text.

function indent( string $text, string|int $indent = 2, bool $indentFirstLine = true, string $delimiter = MMO\core\strings\PHP_EOL ): string
Namespace
MMO\core\strings
$textstring
$indent = 2string | intthe indentation text, or a number of spaces (0 leaves $text untouched)
$indentFirstLine = trueboolif false, the first line is left unindented
$delimiter = MMO\core\strings\PHP_EOLstringthe line separator
returnsstring
indent("a\nb", 2); // " a\n b"
Call graph
function

isAlphaNum

strings.php:96

Test if a string is only made of letters, digits, or the given extra allowed characters.

function isAlphaNum(string $text, array $specialChars = ['_', '-']): bool
Namespace
MMO\core\strings
$textstring
$specialChars = ['_', '-']arraya list of extra allowed characters
returnsbool
isAlphaNum('hello_world-123'); // true
Call graph

Used by (1)

function

isEscaped

strings.php:293

Test if the character at $pos is escaped: preceded by an ODD number of consecutive $escapeChar (an even number means those escape characters escape each other in pairs, leaving $pos itself unescaped).

function isEscaped(string $text, int $pos, string $escapeChar = '\\'): bool
Namespace
MMO\core\strings
$textstring
$posint
$escapeChar = '\\'string
returnsbool
isEscaped('a\t', 2); // true -- the string is a,\,t (single quotes don't turn \t into a tab): one // backslash right before index 2 ('t') -- escaped isEscaped('a\\\\t', 3); // false -- the string is a,\,\,t: two backslashes right before index 3 ('t') // -- they escape each other, so 't' itself is not escaped
Call graph
function

isPlaceholder

strings.php:838

Tells if $text is, as a WHOLE, a single placeholder ({...}) -- e.g. to detect a query/header value that should be captured wholesale rather than matched as a literal template with embedded placeholders.

function isPlaceholder(string $text, array &$info = []): bool
Namespace
MMO\core\strings
$textstring
$info = []array
returnsbool
isPlaceholder('{name}', $info); // true, $info = ['optional' => false, 'path' => 'name', 'type' => ''] isPlaceholder('not a placeholder'); // false
Call graph

Used by (1)

function

isRegex

strings.php:108

Test if a string is a syntactically valid PCRE regular expression (delimiters and all).

function isRegex(string $regex): bool
Namespace
MMO\core\strings
$regexstring
returnsbool
isRegex('/abc/'); // true isRegex('[abc'); // false -- unterminated character class
Call graph

Used by (1)

function

jsonDecode

strings.php:884

Decode a JSON string, optionally tolerating non-standard syntax and templating in {var} values first.

function jsonDecode( string $json, bool $asArray = true, ?array $vars = null, bool $cleanUp = true ): mixed
Namespace
MMO\core\strings
$jsonstring
$asArray = trueboolif true, a JSON object decodes to a plain PHP array instead of stdClass
$vars = nullnull | arrayif given, the raw JSON text is first passed through printf() with these vars (so you can write {var} placeholders directly in the JSON source)
$cleanUp = trueboolif true, tolerate trailing commas and // or *\/ comments, wherever they are -- but never inside a string (neither is standard JSON, and PHP's own json_decode() doesn't support them)
returnsmixed
throwsif the (post-cleanup) text isn't valid JSON
jsonDecode('{"a": 1, "b": 2,}'); // ['a' => 1, 'b' => 2] -- trailing comma tolerated jsonDecode("{\"keep\": 5 // releases\n}"); // ['keep' => 5] jsonDecode('{"cdn": "//cdn.example.com"}'); // ['cdn' => '//cdn.example.com'] -- a string is not a comment jsonDecode('{"a": "{value}"}', true, ['value' => 'hi']); // ['a' => 'hi']
Call graph
function

jsonEncode

strings.php:916

Encode a value as JSON, with a sanity check that guards against a common \json_encode() footgun: silently returning the string 'null' for a value it couldn't actually encode (e.g. a resource, or a NAN/INF float) even though the value wasn't itself null.

function jsonEncode(mixed $data, int $flags = 0, int $depth = 512): string
Namespace
MMO\core\strings
$datamixed
$flags = 0intjson_encode()
$depth = 512int
returnsstring
throwswhen data cannot be encoded
throwswhen the result is 'null' but the data is not null
jsonEncode(['a' => 1]); // '{"a":1}'
Call graph
function

jsonUnicodeDecode

strings.php:970

Reverse of jsonUnicodeEncode(): decode a sequence of JSON unicode escapes (backslash, u, then 4 hex digits, repeated) back to a UTF-8 string.

function jsonUnicodeDecode(string $text): string
Namespace
MMO\core\strings
$textstringa sequence of such 6-character escape groups, no other characters
returnsstring
throwson a malformed or incomplete escape, or an unpaired surrogate
the encoded form of 'A' (@see jsonUnicodeEncode()) decodes back to 'A'
function

jsonUnicodeEncode

strings.php:929

Encode a UTF-8 string as a sequence of JSON \uXXXX unicode escapes (surrogate pairs for anything outside the Basic Multilingual Plane).

function jsonUnicodeEncode(string $text): string
Namespace
MMO\core\strings
$textstring
returnsstring
jsonUnicodeEncode('A'); // the 6-character string: backslash, u, 0, 0, 4, 1
function

length

strings.php:19

Count the number of characters (not bytes) in a UTF-8 string, without needing the mbstring extension.

function length(string $text): int
Namespace
MMO\core\strings
$textstring
returnsint
length('héllo'); // 5 (not 6, even though 'é' is 2 bytes in UTF-8)
Call graph
function

lines

strings.php:381

Split text into lines by $separator, like \explode(), EXCEPT a $separator that falls inside a quoted ($enclosure-delimited) section does not split -- so a CSV-style multi-line quoted field stays on one "line".

function lines( string $text, string $separator = MMO\core\strings\PHP_EOL, string $enclosure = '"', string $escapeChar = '\\' ): array
Namespace
MMO\core\strings
$textstring
$separator = MMO\core\strings\PHP_EOLstringline separator
$enclosure = '"'stringquotation character
$escapeChar = '\\'stringescape character for a literal $enclosure inside a quoted section
returnsarray
lines("a\nb\"c\nd\"\ne", "\n", '"'); // ['a', "b\"c\nd\"", 'e'] -- the 2nd line's embedded \n is preserved
Call graph

Uses (1)

Used by (1)

function

loopTemplate

strings.php:652
Loop a template containing placeholders A placeholder has the following format `{?path:type}` - ?: if the placeholder is optional [optional] - path: a valid json path (`:` MUST be changed to `~2`).function loopTemplate(string $tpl): Generator
Namespace
MMO\core\strings
See
renderTemplate()/matchTemplate() for any of those forms (a route mask like {:integer}, a query capturing {...}, etc. -- they'd just never match/render). Fixed to also accept :, }, ., and *.
`*`: entire data ``: (empty path) entire data `/`: entire data `...`: only the numerical keys of the data `a~2`: will be parsed as `a:` - type: a variable type (`:` allowed) [optional] NOTE: to escape a moustache, use char `\`. WARNING: in php, `\` is written `\\`. so the previous example are : $str = '\\{key}'; //not valid moustache $str = '\\\\{key}'; //valid moustache with `\` before NOTE: previously, only a letter, `?`, or `/` right after `{` was recognized as the start of a real placeholder -- so every documented special-case form starting with something else (bare `{}`, `{:type}`, `{...}`, `{*}`) was rejected as "not a placeholder" and silently left as literal text. This broke
$tplstring
returnsGenerator
\{key} not a moustache\\{key} valid moustache with `\` beforeGet the position of the placeholders: foreach (\MMO\core\strings\loopTemplate('{data/a:type}: {?data/b} \{escaped\}.') as $path => [$type, $optional, $offset, $size]) { \MMO\dump($path, $type, $optional, $offset, $size); }Replace the placeholders by value (WARNING offset are relative to the template being edited. They are the offset on the rendered template) $gen = \MMO\core\strings\loopTemplate('{data/a:type}: {?data/b} \{escaped}.'); while ($gen->valid()) { $path = $gen->key(); [$type, $optional] = $gen->current(); $gen->send($path);//replace the placeholder by this value } \MMO\dump($gen->getReturn());//the rendered template
Call graph
function

matchTemplate

strings.php:785

Match $text against a loopTemplate()-style template, extracting each placeholder's captured (and, if typed, coerced+validated) value into &$matches. Internally builds one single regex out of the template's literal parts (quoted) and each placeholder's type-schema regex (Schema::toRegex(), or .+ for an untyped placeholder).

function matchTemplate( string $tpl, string $text, ?array &$matches = null, ?array $schemas = null ): bool
Namespace
MMO\core\strings
$tplstringthe template
$textstringthe text to match
$matches = nullnull | array
$schemas = nullnull | arraya map of type name => iSchema used to coerce/validate/build the regex for each placeholder's :type. Defaults to \MMO\core\schemas\Schema::GlobalTypes().
returnsbool
matchTemplate('{a}/{b:integer}', 'x/42', $matches); // true, $matches = ['a' => 'x', 'b' => 42] matchTemplate('literal', 'literal'); // true (no placeholder: plain equality)
Call graph
function

normalize

strings.php:57

Normalize text for loose/accent-insensitive equality comparison: safeIdentifier() then lowercase.

function normalize(string $text, string $replace = '_'): string
Namespace
MMO\core\strings
$textstring
$replace = '_'stringthe text to use to replace invalid chars
returnsstring
normalize('Héllo World!'); // 'hello_world_'
Call graph
function

parseDocComment

strings.php:1251

Quickly parse a PHP doc comment (* ... *\/) into its tags. This is the parser commentInformation() (and, through it, the schema-from-doc-comment machinery) is built on.

function parseDocComment(string $text, bool $captureLine = false): array
Namespace
MMO\core\strings
Returns an array. the key ``(empty string) contains global text, else keys are `@xxx` tags. and other text with captureLine = false `[ '' => [ 'this is some text', "\nand other text" ], 'xxx' => [ 'test', 'test2' ] ]` with captureLine = true `[ '' => [ ['this is some text', 0], ["\nand other text", 3] ], 'xxx' => [ ['test', 1], ['test2', 2], ] ]`
$textstring
$captureLine = falseboolif true, add line information
returnsarray
this is some text
Call graph
function

phpStripWhitespace

strings.php:1190

Compact a PHP source string's whitespace (collapse runs of spaces/tabs, strip leading indentation) while preserving line numbers -- unlike stripWhitespace(), this is PHP-token-aware (via \token_get_all()), so it never touches whitespace inside a string/comment token, only real inter-token whitespace and T_WHITESPACE.

function phpStripWhitespace(string $source): string
Namespace
MMO\core\strings
$sourcestringa PHP source string (including the <?php tag)
returnsstring
phpStripWhitespace("<?php\n// comment\n\$a = 1;\n"); // "<?php\n\n$a = 1;\n" -- the comment's own text is dropped, but its line is kept blank
function

position

strings.php:252

The reverse of findOffset(): get the line/column for a given character offset in a text.

function position( string $text, int $offset, ?array $pos = null, string $eol = MMO\core\strings\PHP_EOL ): array
Namespace
MMO\core\strings
$textstring
$offsetintthe offset in text
$pos = nullnull | arraya previously-computed position (from an earlier, smaller offset in the same $text) to resume scanning from instead of the start -- a performance optimization for repeated calls
$eol = MMO\core\strings\PHP_EOLstringend of line delimiter
returnsarray['line' => int, 'column' => int, 'offset' => int]
position("line1\nline2\nline3", 8); // ['line' => 2, 'column' => 3, 'offset' => 8]
function

printf

strings.php:454

Interpolate context values into {key} placeholders in $format. This is the framework's own message formatter (used throughout for log messages, exceptions, etc. -- tLogEmitter), NOT PHP's own \printf()/\sprintf() (no %s-style specifiers here).

function printf(string $format, array $context = [], $fn = 'MMO\\core\\strings\\render'): string
Namespace
MMO\core\strings
A simple literal `strtr()` substitution: unlike [`renderTemplate()`](https://mcp.mmoframework.fr/documentation/mmo.core/php/strings.md#rendertemplate), there's no `:type`/optional syntax and a missing key is simply left as the literal `{key}` text rather than throwing.
$formatstringevery {xxx} placeholder is replaced by $context['xxx']
$context = []array[key => value] to substitute in
$fn = 'MMO\\core\\strings\\render'the function used to convert each value to a string (render()). false to use the raw value as-is.
returnsstring
printf('Hello {name}!', ['name' => 'World']); // 'Hello World!'
Call graph
function

printfd

strings.php:474

Same as printf(), but converts values via describe() instead of render() -- useful for debug messages where you want a value's raw/technical representation rather than its "nice" rendered form.

function printfd(string $format, array $context = []): string
Namespace
MMO\core\strings
$formatstringevery {xxx} placeholder is replaced by $context['xxx']
$context = []array[key => value] to substitute in
returnsstring
printfd('Hello {name}!', ['name' => 'World']); // 'Hello World!'
Call graph
function

regex

strings.php:122

Turn a plain pattern into a valid delimited regular expression, if it isn't one already (a string that already looks like <delim>...<delim><flags> is passed through unchanged, plus $flags appended).

function regex(string $pattern, string $flags = ''): string
Namespace
MMO\core\strings
$patternstring
$flags = ''stringextra PCRE modifiers to append (e.g. 'u', 'i')
returnsstring
regex('abc'); // '~abc~' regex('/abc/', 'i'); // '/abc/i' -- already delimited, $flags just appended
Call graph
function

render

strings.php:493
Render any value into a "nice", human-facing string: - a scalar is cast to string directly - an \MMO\core\interfaces\iRenderable renders itself - an object with __toString() uses that - an iterable has each of its own values rendered (recursively), then joined with $opts['separator'] (or, if given, each passed through $opts['printer'] instead of being recursively rendered) - anything else falls back to [`describe()`](https://mcp.mmoframework.fr/documentation/mmo.core/php/strings.md#describe)function render(mixed $value, array $opts = []): string
Namespace
MMO\core\strings
$valuemixed
$opts = []arrayoptions to render. Available keys (in order of use): 'printer': callable(mixed $value, array $opts), used to render each item of an iterable 'separator': string used to \implode() a rendered iterable's items
returnsstring
render([1, 2, 3]); // '123' (no separator given)
Call graph
function

renderTemplate

strings.php:734

Fill in a loopTemplate()-style template's placeholders with values from $data (by default rendered through render(); pass $printer to customize).

function renderTemplate( string $tpl, ArrayAccess|array $data, ?callable $printer = null, array $opts = [], bool $allowPartial = false, bool $throw = true ): string
Namespace
MMO\core\strings
$tplstringthe template
$dataArrayAccess | arraythe data to inject
$printer = nullnull | callablea Printer function(mixed $value, array $options = [], ?string $type = null) options: - required: {bool} if parameter is required - offset: {int} the offset in the template of the parameter - path: {string} the current path/key of the parameter - size: {int} the size of the current placeholder
$opts = []arrayoptions passed to the printer
$allowPartial = falseboolif true, a placeholder whose value is missing is left as literal {...} text instead of being rendered/throwing
$throw = trueboolif true, throw when a REQUIRED placeholder's value is missing (ignored if $allowPartial)
returnsstring
throwswhen a required value is missing, $allowPartial is false, and $throw is true
{key} required placeholder `key`{?key} optional placeholder key. It won't trigger an exception if it is missing.{key:format}{...:format} special case, will use all the integer keys{:format} special case, will use the data itself{/:format} special case, will use the data itselfrenderTemplate('{name} is {age}', ['name' => 'Marc', 'age' => 40]); // 'Marc is 40' renderTemplate('{?nickname}', [], null, [], true); // '{?nickname}' -- left as-is, missing+optional+allowPartial
Call graph
function

safeIdentifier

strings.php:45

Turn arbitrary text into a safe identifier: strip accents (stripAccents()), trim, and replace every character that isn't a letter/digit/underscore (or in $authorizedChar) with $replace.

function safeIdentifier(string $id, string $replace = '_', string $authorizedChar = ''): string
Namespace
MMO\core\strings
$idstring
$replace = '_'stringthe text to use to replace invalid chars
$authorizedChar = ''stringextra characters (as a regex character-class fragment) to also allow through unchanged
returnsstring
safeIdentifier('Héllo World!'); // 'Hello_World_'
Call graph
function

scoreWord

strings.php:1405

Fuzzy-match score of $w1 against $w2 (e.g. for ranking search results): how much of $w1 is found in $w2, as consecutive runs, weighted by how early those runs start and how long they are.

function scoreWord(string $w1, string $w2): float
Namespace
MMO\core\strings
To compute the score: 1) we compute score of each word : add position, consecutive char add up on same score (ex with 5 chars) v . v . . = 5 + 3 v v . v . = 5 + 5 + 2 2) we add score of consecutive words and square it 3) sum of these scores 4) divide by the square of words count NOTE: this used to be declared to return `int`, which (since this file has no strict_types) silently truncated every fractional score to 0 -- collapsing the whole function down to "1 for a perfect match, 0 for literally anything else" instead of the graded, comparable score it's meant to produce.
$w1stringthe (typically shorter, e.g. a search query) word to look for
$w2stringthe word to search within
returnsfloat1.0 for a perfect match (case/accent-insensitive), down towards 0.0 the less $w1 is found in $w2
scoreWord('hello', 'hello'); // 1.0 -- exact match scoreWord('hel', 'hello'); // partial prefix match, > 0 and < 1 scoreWord('xllo', 'hello'); // lower score: 'x' doesn't match, and the matched run starts mid-word
Call graph

Uses (1)

function

stripAccents

strings.php:1601

Replace every accented Latin character in $value with its plain-letter equivalent (getAccents()).

function stripAccents(string $value): string
Namespace
MMO\core\strings
$valuestring
returnsstring
stripAccents('héllo wörld'); // 'hello world'
Call graph
function

stripWhitespace

strings.php:1171

Collapse runs of horizontal whitespace to a single space, strip leading indentation on every line, and remove blank lines -- a generic text-compacting helper (NOT PHP-token-aware; phpStripWhitespace() for that, which additionally understands comments/strings and can't corrupt them).

function stripWhitespace(string $source): string
Namespace
MMO\core\strings
$sourcestring
returnsstring
stripWhitespace("a b\n\n\nc"); // "a b\nc"
function

textRegex

strings.php:1616

Build a case/accent-insensitive regex that matches $value literally, but where every letter also matches any of its accented forms (e.g. 'e' in the pattern also matches 'é', 'è', 'ê', ...).

function textRegex(string $value, ?string $delimiter = '/', bool $lowercase = true): string
Namespace
MMO\core\strings
$valuestring
$delimiter = '/'null | stringif null, won't add the modifier and delimeter (warning you need to use u modifier for utf-8 to work)
$lowercase = trueboolif true, use i modifier and set the value to lowercase
returnsstring
$re = textRegex('cafe'); // '/[c...][a...]f[e...]/ui' -- accent character-classes per letter preg_match($re, 'café'); // 1 -- matches despite the accent
Call graph
function

utf8Split

strings.php:1642

Split a UTF-8 string into an array of its characters (not bytes -- a multi-byte character stays whole).

function utf8Split(string $text): array
Namespace
MMO\core\strings
$textstringMUST be a valid UTF-8 encoded string
returnsarray
throwsif $text isn't valid UTF-8 (only checked when the mbstring extension is available)
utf8Split('héllo'); // ['h', 'é', 'l', 'l', 'o'] -- 5 characters, even though 'é' is 2 bytes
function

UTF8ToHtml

strings.php:435

Convert every 4-byte UTF-8 character (i.e. outside the Basic Multilingual Plane -- emoji, some rare CJK, ...) in $text to a numeric HTML entity, leaving everything else untouched.

function UTF8ToHtml($text): string
Namespace
MMO\core\strings
$text
returnsstring
🕱 => &#128369;