Tradotto automaticamente dall’inglese, che è la versione originale.
campi e metodi delle stringhe
Testo. Una stringa che contiene un numero può usare anche i metodi dei numeri.
Il testo è una string: qualsiasi cosa tra virgolette. 'Single quotes' mantengono esattamente ciò che scrivi, e "double quotes" inseriscono ciò che si trova in { }, quindi "Hello { $name }" legge la variabile. Per un testo su più righe, scrivi un blocco di testo tra le righe ```, che mantiene ogni a capo come scritto.
I metodi di testo non modificano mai il testo su cui vengono chiamati; ognuno restituisce un nuovo testo (oppure un numero, una lista o un bool), quindi concatenali o conserva il risultato in una variabile:
<let name="name" value="' ada LOVELACE '" />
<let name="tidy" value="$name->trim()->title()" />
<echo value="$tidy" /> <!-- 'Ada Lovelace' because the spaces go and each word gets a capital -->
<echo value="$name" /> <!-- ' ada LOVELACE ' because the text itself is unchanged -->
$name = ' ada LOVELACE '
$tidy = $name->trim()->title()
echo $tidy // 'Ada Lovelace' because the spaces go and each word gets a capital
echo $name // ' ada LOVELACE ' because the text itself is unchanged
Le posizioni partono da 0, e una posizione negativa conta dalla fine. Un carattere come un'emoji occupa due posizioni, e nessun metodo lo divide a metà. I confronti distinguono le maiuscole dalle minuscole, a meno che tu non passi il flag ignore_case.
Un campo è un dato semplice sul valore, letto con un punto e senza parentesi: $value.name. Un metodo richiede argomenti o esegue un'operazione, e si chiama con ->: $value->name(arguments), oppure passando il valore con la pipe: $value |> name(arguments).
Il testo dopo la prima volta che compare il testo (o l'ultima, con last), oppure l'intero testo se non compare: 'a.tar.gz'->after('.', last) è gz.
->after(text, last?) restituisce il testo dopo la prima volta che text compare, oppure dopo l'ultima volta con last. Quando text non c'è, ottieni indietro l'intero testo:
<let name="file" value="'archive.tar.gz'" />
<echo value="$file->after('.')" /> <!-- 'tar.gz' because it cuts at the first dot -->
<echo value="$file->after('.', last)" /> <!-- 'gz' because it cuts at the last dot -->
<echo value="'no-at-sign'->after('@')" /> <!-- 'no-at-sign' because there is no @ to cut at -->
$file = 'archive.tar.gz'
echo $file->after('.') // 'tar.gz' because it cuts at the first dot
echo $file->after('.', last) // 'gz' because it cuts at the last dot
echo 'no-at-sign'->after('@') // 'no-at-sign' because there is no @ to cut at
Il testo prima della prima volta che compare il testo (o l'ultima, con last), oppure l'intero testo se non compare: 'a.tar.gz'->before('.', last) è a.tar.
->before(text, last?) restituisce il testo prima della prima volta che text compare, oppure prima dell'ultima volta con last. Quando text non c'è, ottieni indietro l'intero testo:
<let name="email" value="'joan@example.com'" />
<echo value="$email->before('@')" /> <!-- 'joan' -->
<echo value="'archive.tar.gz'->before('.', last)" /> <!-- 'archive.tar' because it cuts at the last dot -->
$email = 'joan@example.com'
echo $email->before('@') // 'joan'
echo 'archive.tar.gz'->before('.', last) // 'archive.tar' because it cuts at the last dot
Le parti del testo comprese tra righe vuote, ciascuna privata degli a capo che la circondano: 'a\nb\n\nc'->blocks() è ['a\nb', 'c'].
->blocks() divide il testo nelle righe vuote, quindi ogni blocco è un gruppo di righe. Un singolo a capo resta dentro un blocco; solo una riga vuota ne inizia uno nuovo. Ogni blocco viene privato degli a capo che lo circondano:
<let name="pantry">```text
tea
milk
flour
sugar
eggs
```</let>
<let name="shelves" value="$pantry->blocks()" />
<echo value="$shelves->count()" /> <!-- 2 because one blank line splits the text in two -->
<echo value="$shelves->map(.lines()->count())" /> <!-- [2, 3] because the first block has 2 lines and the second 3 -->
$pantry = ```text
tea
milk
flour
sugar
eggs
```
$shelves = $pantry->blocks()
echo $shelves->count() // 2 because one blank line splits the text in two
echo $shelves->map(.lines()->count()) // [2, 3] because the first block has 2 lines and the second 3
->capitalize() rende maiuscola la prima lettera e lascia invariato il resto:
<echo value="'élan and style'->capitalize()" /> <!-- 'Élan and style' because only the first letter changes -->
<echo value="'iPhone'->capitalize()" /> <!-- 'IPhone' -->
echo 'élan and style'->capitalize() // 'Élan and style' because only the first letter changes
echo 'iPhone'->capitalize() // 'IPhone'
Il testo come identificatore in uno stile: 'User ID'->case(snake) è user_id, kebab dà user-id, camel userId e pascal UserId.
->case(style) riscrive il testo come nome in uno stile: snake (user_id), kebab (user-id), camel (userId) o pascal (UserId). Trova le parole sia negli spazi, nei separatori sia nei cambi di maiuscola, così puoi passare da qualsiasi stile a qualsiasi altro:
->chars() restituisce i caratteri come lista, un testo per ciascuno. Un carattere come un'emoji è un solo elemento, comunque sia memorizzato:
<echo value="'tea'->chars()" /> <!-- ['t', 'e', 'a'] -->
<echo value="'👍🏽x'->chars()->count()" /> <!-- 2 because the thumb and its skin tone are one character -->
echo 'tea'->chars() // ['t', 'e', 'a']
echo '👍🏽x'->chars()->count() // 2 because the thumb and its skin tone are one character
->escape() rende il testo sicuro da inserire in HTML: <, >, & e le virgolette diventano entità, così ciò che un utente ha digitato viene mostrato come testo e non diventa markup:
<echo value="'<b>Tea & milk</b>'->escape()" /> <!-- '<b>Tea & milk</b>' -->
echo '<b>Tea & milk</b>'->escape() // '<b>Tea & milk</b>'
Le pagine già eseguono l'escape di ciò che stampano; questo serve per l'HTML che costruisci tu.
Il testo come righe di caratteri, una lista per riga, per mappe e labirinti: '#.\n.#'->grid() è [['#', '.'], ['.', '#']]. Un a capo alla fine non aggiunge una riga vuota. Leggi una cella con $grid[row][column], e scorri le sue righe o colonne con ->cells(rows) o ->cells(columns).
->grid() trasforma righe di caratteri in righe di singoli caratteri, quindi $grid[row][column] è un solo carattere. La riga 0 è la prima riga in alto e la colonna 0 il primo carattere. Un a capo alla fine non aggiunge una riga vuota:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<echo value="$plot" /> <!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is #.# and column 1 is its middle -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is ..# and column 2 is its last -->
$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot // [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1] // '.' because row 0 is #.# and column 1 is its middle
echo $plot[1][2] // '#' because row 1 is ..# and column 2 is its last
L'HMAC del testo con una chiave segreta, in esadecimale (SHA-256 per impostazione predefinita), come si creano le firme dei webhook. Confronta le firme con @secure_equals().
->hmac(key, algorithm?) firma il testo con una chiave segreta e restituisce la firma in esadecimale, SHA-256 a meno che non passi sha1 o sha512. È il modo in cui i webhook dimostrano da dove proviene un messaggio. Confronta le firme con @secure_equals(), che richiede lo stesso tempo indipendentemente da quanto le due coincidano:
<let name="body" value="'{"id": 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="$signature->count()" /> <!-- 64 because SHA-256 in hex is 64 characters -->
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true because the same key signs the same text the same way -->
$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo $signature->count() // 64 because SHA-256 in hex is 64 characters
echo @secure_equals($signature, $body->hmac('whsec_test')) // true because the same key signs the same text the same way
Parametro
Accetta
keyobbligatorio
qualsiasi valore
algorithmfacoltativo
una di queste parole: sha256|sha1|sha512
Gli argomenti possono essere con nome: ->hmac(…, algorithm: …).
Esempio
<echo>{ '{"id": 1}'->hmac('whsec_test') }</echo>
echo '{"id": 1}'->hmac('whsec_test')
#string->index_of(text, ignore_case?: bool, last?: bool)→ number
Dove il testo compare per la prima volta, oppure con last, dove compare per l'ultima volta; -1 se non compare. Con ignore_case, maiuscole e minuscole coincidono.
->index_of(text, ignore_case?, last?) restituisce la posizione in cui text compare per la prima volta, oppure con last, dove compare per l'ultima volta. Restituisce -1 quando text non c'è:
Vero quando il testo è vuoto o contiene solo spazi bianchi.
->is_blank() è true quando il testo è vuoto o contiene solo spazi, tabulazioni e a capo. Usalo per controllare ciò che un utente ha digitato in un modulo:
Vero quando l'intero testo è un numero, come '42', '-3.5' o '1e3'. Sono ammessi spazi attorno al numero.
->is_numeric() è vero quando l'intero testo è un numero, come '42', '-3.5' o '1e3'. Sono ammessi spazi attorno al numero:
<echo value="'42'->is_numeric()" /> <!-- true -->
<echo value="' -3.5 '->is_numeric()" /> <!-- true because the spaces around it are fine -->
<echo value="'42 cats'->is_numeric()" /> <!-- false because cats isn't part of a number -->
echo '42'->is_numeric() // true
echo ' -3.5 '->is_numeric() // true because the spaces around it are fine
echo '42 cats'->is_numeric() // false because cats isn't part of a number
->lines() restituisce un testo per ogni riga. Una riga vuota dà un testo vuoto, così puoi trovare le interruzioni tra i gruppi:
<let name="note">```text
tea
milk
juice
```</let>
<echo value="$note->lines()" /> <!-- ['tea', 'milk', '', 'juice'] -->
<echo value="$note->lines()->count()" /> <!-- 4 because the blank line is a line too -->
$note = ```text
tea
milk
juice
```
echo $note->lines() // ['tea', 'milk', '', 'juice']
echo $note->lines()->count() // 4 because the blank line is a line too
->blocks() divide invece il testo nelle righe vuote.
Il testo con ogni carattere sostituito da char (* per impostazione predefinita), tranne gli ultimi keep_end caratteri: ->mask('*', keep_end: 4) mostra solo gli ultimi quattro.
->mask(char?, keep_end?) nasconde il testo dietro un carattere, * a meno che tu non ne indichi un altro, mantenendo gli ultimi keep_end caratteri perché il lettore possa riconoscerlo:
<echo value="'4242424242424242'->mask('*', keep_end: 4)" /> <!-- '************4242' because only the last 4 show -->
<echo value="'secret'->mask()" /> <!-- '******' -->
echo '4242424242424242'->mask('*', keep_end: 4) // '************4242' because only the last 4 show
echo 'secret'->mask() // '******'
Vero quando il testo corrisponde a un'espressione regolare: ->matches(/^[a-z]+$/i).
->matches(pattern) è vero quando un'espressione regolare trova una corrispondenza nel testo. Ancorala con ^ e $ per verificare l'intero testo:
<echo value="'Tea'->matches(/^[a-z]+$/i)" /> <!-- true because i ignores case -->
<echo value="'Tea2'->matches(/^[a-z]+$/i)" /> <!-- false because 2 isn't a letter -->
echo 'Tea'->matches(/^[a-z]+$/i) // true because i ignores case
echo 'Tea2'->matches(/^[a-z]+$/i) // false because 2 isn't a letter
Normalizza Unicode usando la forma indicata (NFC per impostazione predefinita).
->normalize_unicode(form?) fa sì che testi che appaiono uguali si confrontino come uguali. é può essere memorizzato come un solo carattere o come e più un accento; NFC (il predefinito) li unisce, NFD li separa:
<echo value="'café'->normalize_unicode(NFD)->count()" /> <!-- 5 because NFD stores é as e and an accent -->
<echo value="'café'->normalize_unicode()->count()" /> <!-- 4 -->
echo 'café'->normalize_unicode(NFD)->count() // 5 because NFD stores é as e and an accent
echo 'café'->normalize_unicode()->count() // 4
Ogni numero nel testo, in ordine, come numeri: 'x=-3, y=12'->numbers() è [-3, 12]. Un meno rende il numero negativo a meno che una lettera o una cifra non compaia subito prima; quindi '1-3'->numbers() è [1, 3].
->numbers() restituisce ogni numero scritto nel testo, in ordine, come numeri. Un meno conta come segno quando non è unito a nulla alla sua sinistra, come in x=-3; tra due numeri, come in 1-3, è un trattino:
<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->
echo 'move 3 boxes from -1 to 12'->numbers() // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers() // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers() // [2.5, 4]
Il testo riempito alla fine fino a width, oppure all'inizio con start: '7'->pad(3, '0', start) è 007.
->pad(width, char?, start?) aggiunge un carattere, uno spazio a meno che tu non ne indichi un altro, finché il testo non raggiunge width caratteri. Riempie alla fine, oppure all'inizio con start. Il testo già di quella lunghezza non viene modificato:
<echo value="'7'->pad(3, '0', start)" /> <!-- '007' because two zeros go in front -->
<echo value="'tea'->pad(5, '.')" /> <!-- 'tea..' -->
<echo value="'teapot'->pad(3)" /> <!-- 'teapot' because it is already longer than 3 -->
echo '7'->pad(3, '0', start) // '007' because two zeros go in front
echo 'tea'->pad(5, '.') // 'tea..'
echo 'teapot'->pad(3) // 'teapot' because it is already longer than 3
The text with every old replaced by new. old can be a regex: ->replace(/\s+/, ' '), and new can use its groups as $1 or $. With ignore_case, plain text matches in any case.
->replace(old, new, ignore_case?) sostituisce ogni old con new. old può essere un'espressione regolare, e in quel caso new può usare ciò che i suoi gruppi hanno trovato come $1 o ${name}:
<echo value="'banana'->replace('a', 'o')" /> <!-- 'bonono' because every a changes -->
<echo value="'Tea'->replace('t', 'p', ignore_case)" /> <!-- 'pea' because T matches t -->
<echo value="'too many spaces'->replace(/\s+/, ' ')" /> <!-- 'too many spaces' -->
<echo value="'2026-12-01'->replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1')" /> <!-- '01/12/2026' because the groups swap places -->
echo 'banana'->replace('a', 'o') // 'bonono' because every a changes
echo 'Tea'->replace('t', 'p', ignore_case) // 'pea' because T matches t
echo 'too many spaces'->replace(/\s+/, ' ') // 'too many spaces'
echo '2026-12-01'->replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1') // '01/12/2026' because the groups swap places
Parametro
Accetta
oldobbligatorio
qualsiasi valore
newobbligatorio
qualsiasi valore
ignore_casefacoltativo
un flag: ignore_case oppure not ignore_case
Gli argomenti possono essere con nome: ->replace(…, new: …, ignore_case: …).
->sha256() restituisce l'hash SHA-256 del testo in esadecimale, 64 caratteri. Lo stesso testo dà sempre lo stesso hash, e ogni modifica ne dà uno diverso:
<echo value="'tea'->sha256()->count()" /> <!-- 64 -->
<echo value="'tea'->sha256() == 'tea'->sha256()" /> <!-- true because the same text gives the same hash -->
<echo value="'tea'->sha256() == 'Tea'->sha256()" /> <!-- false because one letter changed -->
echo 'tea'->sha256()->count() // 64
echo 'tea'->sha256() == 'tea'->sha256() // true because the same text gives the same hash
echo 'tea'->sha256() == 'Tea'->sha256() // false because one letter changed
Every place a mask fits (->shapes(Tree), or ->shapes([Block, Ell]) for several), and every square, rectangle, line or circle (name one or several: ->shapes(square, circle, of: '#')) made by the cells that hold of: (a value, or a regex). It looks through text (each line a row, each character a cell, a blank line between layers), a list of values (one row), a grid ($grid[row][column]) or a 3D list ($cube[layer][row][column]); the built-in shapes also take a list of points { row, column }. A mask is a type that extends Mask: its layout is a picture, one character a cell, and each character matches a cell holding the same character, unless its symbols say otherwise (a value, a regex, a fn(cell), or any for a cell that isn't part of the shape). Each match is { kind, points }: kind is the mask's name or the shape, and each point is { row, column, value } (with symbol for a mask, and layer in 3D). With rotated, a mask is tried turned every way the input allows (back to front in a row, the four quarter turns in a grid, all 24 ways round in 3D), and squares, rectangles and lines may lean. A line needs size:, and a circle radius: and distance: straight (the default), steps or moves.
->shapes(mask?, square?, rectangle?, line?, circle?, of?, rotated?, size?, radius?, distance?) finds shapes drawn in text. Each line is a row and each character a cell, so the text doesn't need ->grid() first, and a blank line starts the next layer of a 3D input. It works as the list method does: name a mask first (a type that extends Mask, or a list of them), or one of the built-in shapes with of: to say which cells make it. Each match comes back as { kind, points }, and each point says its row, column, value and the mask's symbol drawn over it. See list ->shapes() for every argument.
<let name="orchard">```text
#.#.#
.#...
#.#.#
```</let>
<type name="Tree" extends="Mask">
<field name="layout" default="```text
#.#
.#.
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<echo value="$orchard->shapes(Tree)->count()" /> <!-- 1 because the V of three trees fits only at the top left -->
<echo value="$orchard->shapes(Tree, rotated)->count()" /> <!-- 4 because turned upside down and on its sides it fits three more places -->
<echo value="$orchard->shapes(Tree)->first().points->map(.column)" /> <!-- [0, 2, 1] because the points come in reading order: the top two, then the middle -->
$orchard = ```text
#.#.#
.#...
#.#.#
```
type Tree extends Mask {
layout: ```text
#.#
.#.
```
symbols: { '.': any }
}
echo $orchard->shapes(Tree)->count() // 1 because the V of three trees fits only at the top left
echo $orchard->shapes(Tree, rotated)->count() // 4 because turned upside down and on its sides it fits three more places
echo $orchard->shapes(Tree)->first().points->map(.column) // [0, 2, 1] because the points come in reading order: the top two, then the middle
Parte del testo; le posizioni negative contano dalla fine.
->slice(start, end?) restituisce i caratteri dalla posizione start fino a, escluso, end, oppure fino alla fine del testo. Le posizioni negative contano dalla fine:
<let name="word" value="'teapot'" />
<echo value="$word->slice(0, 3)" /> <!-- 'tea' because it stops before position 3 -->
<echo value="$word->slice(3)" /> <!-- 'pot' -->
<echo value="$word->slice(-3)" /> <!-- 'pot' because -3 is three from the end -->
$word = 'teapot'
echo $word->slice(0, 3) // 'tea' because it stops before position 3
echo $word->slice(3) // 'pot'
echo $word->slice(-3) // 'pot' because -3 is three from the end
Le parti tra ogni separatore (o tra gli spazi), come lista. Il separatore può essere una regex: ->split(/\s*,\s*/).
->split(separator?) divide il testo a ogni separatore e restituisce le parti come lista. Senza separatore divide agli spazi. Il separatore può essere un'espressione regolare:
<echo value="'tea,milk,juice'->split(',')" /> <!-- ['tea', 'milk', 'juice'] -->
<echo value="'tea milk'->split()" /> <!-- ['tea', 'milk'] -->
<echo value="'a, b,c'->split(/\s*,\s*/)" /> <!-- ['a', 'b', 'c'] because the spaces around each comma go too -->
echo 'tea,milk,juice'->split(',') // ['tea', 'milk', 'juice']
echo 'tea milk'->split() // ['tea', 'milk']
echo 'a, b,c'->split(/\s*,\s*/) // ['a', 'b', 'c'] because the spaces around each comma go too
Il testo senza spazi iniziali e finali, con ogni sequenza di spazi, tabulazioni e a capo interni sostituita da un solo spazio.
->squish() elimina gli spazi all'inizio e alla fine del testo e trasforma ogni sequenza di spazi, tabulazioni e interruzioni di riga al suo interno in un solo spazio:
<echo value="' too many spaces '->squish()" /> <!-- 'too many spaces' -->
echo ' too many spaces '->squish() // 'too many spaces'
Il testo senza un prefisso, un suffisso o entrambi esatti, dove presenti: 'v1.2'->strip(prefix: 'v'), 'a.txt'->strip(suffix: '.txt').
->strip(prefix?, suffix?) toglie un prefisso, un suffisso o entrambi esatti, dove ci sono. A differenza di ->trim(), rimuove l'intero pezzo una sola volta, non ogni carattere:
<echo value="'v1.2'->strip(prefix: 'v')" /> <!-- '1.2' -->
<echo value="'notes.txt'->strip(suffix: '.txt')" /> <!-- 'notes' -->
<echo value="'[tea]'->strip(prefix: '[', suffix: ']')" /> <!-- 'tea' -->
<echo value="'tea'->strip(prefix: 'x')" /> <!-- 'tea' because there is no x to take off -->
echo 'v1.2'->strip(prefix: 'v') // '1.2'
echo 'notes.txt'->strip(suffix: '.txt') // 'notes'
echo '[tea]'->strip(prefix: '[', suffix: ']') // 'tea'
echo 'tea'->strip(prefix: 'x') // 'tea' because there is no x to take off
Il testo codificato in base64. Con url: true, è base64 sicuro per URL senza padding.
->to_base64(url?) codifica il testo in base64, che usa solo lettere, cifre, +, / e =, così può viaggiare dove altri caratteri non possono, come un header HTTP. Con url, usa invece - e _ e omette il padding =, così può stare in un URL. Il risultato è un valore base64, il cui ->decode() restituisce il testo originale:
<echo value="'tea'->to_base64()" /> <!-- 'dGVh' -->
<echo value="'tea?'->to_base64()" /> <!-- 'dGVhPw==' -->
<echo value="'tea?'->to_base64(url)" /> <!-- 'dGVhPw' because url leaves off the padding -->
<echo value="'tea'->to_base64()->decode()" /> <!-- 'tea' because the base64 value decodes back to the text -->
echo 'tea'->to_base64() // 'dGVh'
echo 'tea?'->to_base64() // 'dGVhPw=='
echo 'tea?'->to_base64(url) // 'dGVhPw' because url leaves off the padding
echo 'tea'->to_base64()->decode() // 'tea' because the base64 value decodes back to the text
Legge il testo come data: '2026-11-22'->to_date(), oppure, con il formato in cui è scritto, '22-11-2026'->to_date(dd-MM-yyyy).
->to_date(format?) legge il testo come data. Le date scritte in formato ISO, come '2026-11-22' o '2026-11-22 14:30', non richiedono un formato; per ogni altro formato, indica il pattern in cui è scritta:
<let name="day" value="'2026-11-22'->to_date()" />
<echo value="$day.year" /> <!-- 2026 -->
<echo value="'22-11-2026'->to_date(dd-MM-yyyy).month" /> <!-- 11 because the pattern says the month is in the middle -->
$day = '2026-11-22'->to_date()
echo $day.year // 2026
echo '22-11-2026'->to_date(dd-MM-yyyy).month // 11 because the pattern says the month is in the middle
Il testo come numero intero, oppure default se non lo è.
->to_int(default?) legge il testo come numero intero, scartando tutto ciò che segue il punto decimale. Quando il testo non è un numero, ottieni default; senza un valore di default, è un errore di tipo, quindi passa un default per i testi di cui non sei sicuro:
<echo value="'42'->to_int()" /> <!-- 42 -->
<echo value="'3.7'->to_int()" /> <!-- 3 because the .7 is dropped -->
<echo value="'abc'->to_int(-1)" /> <!-- -1 because abc isn't a number -->
echo '42'->to_int() // 42
echo '3.7'->to_int() // 3 because the .7 is dropped
echo 'abc'->to_int(-1) // -1 because abc isn't a number
->to_number(default?) legge il testo come numero, decimali compresi. Quando il testo non è un numero, ottieni default; senza un valore di default, è un errore di tipo che lo segnala:
<echo value="'3.7'->to_number()" /> <!-- 3.7 -->
<echo value="'x'->to_number(0)" /> <!-- 0 because x isn't a number, so the default is used -->
<echo value="'x'->to_number(null)" /> <!-- null -->
echo '3.7'->to_number() // 3.7
echo 'x'->to_number(0) // 0 because x isn't a number, so the default is used
echo 'x'->to_number(null) // null
Il testo senza spazi (o i caratteri indicati) a una o entrambe le estremità, oppure solo all'inizio o alla fine: ->trim(start), ->trim('/', end).
->trim(characters?, start?, end?) rimuove spazi, tabulazioni e interruzioni di riga da entrambe le estremità, oppure i caratteri che indichi. Con start o end taglia solo quel lato:
<echo value="' tea '->trim()" /> <!-- 'tea' -->
<echo value="'//path//'->trim('/')" /> <!-- 'path' -->
<echo value="' tea '->trim(start)" /> <!-- 'tea ' because only the start is trimmed -->
echo ' tea '->trim() // 'tea'
echo '//path//'->trim('/') // 'path'
echo ' tea '->trim(start) // 'tea ' because only the start is trimmed
Parametro
Accetta
charactersfacoltativo
qualsiasi valore
startfacoltativo
un flag: start o not start
endoptional
un flag: end oppure not end
Gli argomenti possono avere un nome: ->trim(…, start: …, end: …).
Accorcia il testo a length, aggiungendo suffix (… per impostazione predefinita).
->truncate(length, suffix?) mantiene i primi length caratteri e aggiunge un suffisso, … salvo che tu ne indichi un altro, se c'era di più. Il testo che già rientra resta invariato:
Le parole del testo, come lista, senza spazi né punteggiatura. Contano le lettere di qualsiasi alfabeto, e don't o well-known sono una sola parola.
->words() restituisce le parole del testo, senza gli spazi e la punteggiatura tra di esse. Contano le lettere di qualsiasi alfabeto, e don't o well-known restano una sola parola:
<echo value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value=""Don't stop"->words()->count()" /> <!-- 2 because don't is one word -->
echo 'Hello, world!'->words() // ['Hello', 'world']
echo "Don't stop"->words()->count() // 2 because don't is one word
Esempio
<echo>{ 'Hello, world! A well-known phrase.'->words() }</echo>
echo 'Hello, world! A well-known phrase.'->words()
Il testo con interruzioni di riga tra le parole, in modo che nessuna riga superi width (a meno che una singola parola non sia più lunga). Funziona bene con @terminal_width().
->wrap(width) inserisce interruzioni di riga tra le parole in modo che nessuna riga superi width, a meno che una singola parola non sia più lunga. È adatto al testo per un terminale, come uno largo @terminal_width():
<let name="lines" value="'Ann went home early'->wrap(width: 9)->lines()" />
<echo value="$lines" /> <!-- ['Ann went', 'home', 'early'] because home early would be 10 characters -->
$lines = 'Ann went home early'->wrap(width: 9)->lines()
echo $lines // ['Ann went', 'home', 'early'] because home early would be 10 characters