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
Il testo con ogni old sostituito da new. old può essere una regex: ->replace(/\s+/, ' '), e new può usarne i gruppi come $1 o ${name}. Con ignore_case, il testo semplice corrisponde in qualsiasi maiuscolo o minuscolo.
->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
Ogni punto in cui una maschera combacia (->shapes(Tree), oppure ->shapes([Block, Ell]) per più di una) e ogni quadrato, rettangolo, linea o cerchio (indica uno o più nomi: ->shapes(square, circle, of: '#')) formato dalle celle che contengono of: (un valore o una regex). Analizza il testo (ogni riga è una riga, ogni carattere una cella, una riga vuota tra i livelli), una lista di valori (una riga), una griglia ($grid[row][column]) o una lista 3D ($cube[layer][row][column]); le forme integrate accettano anche una lista di punti { row, column }. Una maschera è un tipo che estende Mask: il suo layout è un disegno, un carattere per cella, e ogni carattere combacia con una cella che contiene lo stesso carattere, a meno che i suoi simboli non dicano altrimenti (un valore, una regex, una fn(cell), lo stesso per le celle che contengono tutte un unico valore, oppure any per una cella che non fa parte della forma). Anche un layout può essere una regex, che legge le celle lungo una riga, di qualsiasi lunghezza. Con repeated, la maschera viene ripetuta più volte a partire dall'angolo in alto a sinistra fino a coprire l'input, con le copie ai bordi tagliate: ogni copia deve contenere ciò che contiene la prima, e ogni corrispondenza è la prima copia, con copies, quante ce ne sono state (un layout regex dà una corrispondenza per ogni dimensione che entra, dalla più piccola). blank: (un valore, una regex o una fn(cell)) indica le celle dell'input che combaciano con qualsiasi cosa, e copies e same celle si riempiono a vicenda gli spazi vuoti. Ogni corrispondenza è { kind, points }: kind è il nome della maschera o della forma, e ogni punto è { row, column, value } (con symbol per una maschera, e layer in 3D). Con rotated, una maschera viene provata ruotata in tutti i modi consentiti dall'input (avanti e indietro in una riga, le quattro rotazioni di un quarto in una griglia, tutti i 24 modi in 3D), e quadrati, rettangoli e linee possono essere inclinati. Una linea richiede size:, e un cerchio richiede radius: e distance: dritto (il valore predefinito), steps o moves.
->shapes(mask?, square?, rectangle?, line?, circle?, of?, rotated?, size?, radius?, distance?, repeated?, blank?) trova forme disegnate nel testo. Ogni riga è una riga di celle e ogni carattere una cella, quindi il testo non deve prima essere ->grid(), e una riga vuota inizia il livello successivo di un input 3D. Funziona come il metodo list: indica prima una maschera (un tipo che extends Mask, oppure una lista di essi), oppure una delle forme predefinite con of: per dire quali celle la compongono. Ogni corrispondenza torna come { kind, points }, e ogni punto indica il proprio row, column, value e la symbol della maschera disegnata sopra. Il layout di una maschera può essere una regex, che legge lungo ogni riga, di qualsiasi lunghezza. repeated applica la maschera su tutto il testo e restituisce la prima copia, e blank: '?' permette ai ? di adattarsi a qualsiasi cosa. Vedi list ->shapes() per tutti gli argomenti, e masks per la guida.
<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 -->
<type name="Instructions" description="A printer's instructions: one or more colours." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<echo value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first().points->count()" /> <!-- 3 because rgb, repeated and cut off, prints the whole barcode -->
<echo value="'?rv'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 2 because vr fits: the ? is a v -->
$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
/// A printer's instructions: one or more colours.
type Instructions extends Mask {
layout: /[roygbv]+/
}
echo 'rgbrgbrgbr'->shapes(Instructions, repeated)->first().points->count() // 3 because rgb, repeated and cut off, prints the whole barcode
echo '?rv'->shapes(Instructions, repeated, blank: '?')->first().points->count() // 2 because vr fits: the ? is a v
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
Il codice come HTML evidenziato per un <pre>, colorato con le grammatiche usate dall'estensione VS Code: ogni token in uno <span class="hl-kw"> (hl-com, hl-str, hl-num, hl-kw, hl-op, hl-fn, hl-type, hl-var, hl-tag, hl-attr, hl-expr, hl-re) perché un foglio di stile lo colori. lang è kscript (il valore predefinito), ks.xml, html (una pagina), ks.css, text, oppure un linguaggio che VS Code conosce: css, js, ts, json, sql, sh, yaml, python...