Strings and interpolation
A string is text. Write it in double quotes, and you can write a variable inside it. Binary data
has its own type, bytes.
Values written in the code
You can write a value directly in your program: a number, a string, true, false or null.
A number can have underscores between its digits, and it can be written in base 16, base 2 or base 8. A leading zero has no special meaning, so 017 is seventeen. A number followed by a unit, such as 30s or 1h30m, is a duration (a length of time).
A string in single quotes keeps every character as you typed it. A string in double quotes inserts the values of your variables and reads escapes such as \n. A heredoc is a string that covers several lines.
An html template, written `html... , is a piece of a web page. Its type is Core\Html\Markup`. Every value you insert into it is escaped, so a value cannot add a tag.
The examples below show the ways to write a number, the two kinds of quotes, a message built from a template, a page fragment with inserted values, the escapes of a double-quoted string, durations, and a program that joins markup with . and does not compile.
The ways to write a number
<?nvs// A number can be written in more than one way. Underscores between digits make// a long number easier to read, and the value stays the same. You can also write// a number in base sixteen (`0x`), base two (`0b`) or base eight (`0o`).
int $seats = 1_000_000;int $mask = 0xFF;int $flags = 0b1011;int $mode = 0o644;
echo $seats, ' ', $mask, ' ', $flags, ' ', $mode, "\n";
// A zero at the front is only a zero, so `017` is seventeen.// PHP and C read `017` as base eight, which is fifteen.int $seventeen = 017;
echo $seventeen, "\n";
// A number with a dot or an exponent in it is a float. The digits before the// dot or after it may be left out.float $half = .5;float $five = 5.;float $thousand = 1e3;
echo $half, ' ', $five, ' ', $thousand, "\n";1000000 255 11 420170.5 5 1000The two kinds of quote
<?nvs// Single quotes keep the text exactly as you typed it. Double quotes fill in// the values of your variables and turn an escape such as `\n` into the// character it stands for.
class Guest{ public string $name = 'Ada';
public function shouting(): string { return Core\Str::upper($this->name); }}
string $who = 'Ada';
echo 'Dear $who,', "\n";echo "Dear $who,", "\n";
// Braces let you put a whole expression in the text. Anything that starts// with a variable works: a key of an array, a property, or a method call.array<string> $city = ['home' => 'Vienna'];Guest $guest = new Guest();
echo "You are in $city[home] today.\n";echo "Room for {$guest->name}, who signs as {$guest->shouting()}.\n";
// A brace with no variable after it is just a brace, and a backslash the// language does not know keeps its backslash.echo "{plain} and \q\n";Dear $who,Dear Ada,You are in Vienna today.Room for Ada, who signs as ADA.{plain} and \qA message to a customer
<?nvs// A confirmation message, written as one block with a heredoc. The text sits// in the program the way it will look to the customer, and the values are// filled in where they appear. The closing marker sets the indentation, so// the lines can stay lined up with the code.
string $who = 'Ada';int $order = 1042;decimal $total = 24.90;Core\Time\Duration $window = 2w;
echo <<<TEXT Hi $who,
Order #$order is on its way. The total was $total euro. You can send it back within $window.
Thank you! TEXT;echo "\n";
// The second kind of heredoc quotes the marker, and then nothing is filled// in. It is what you want for a template you hand to something else.echo <<<'TEXT' Hi $who, your order #$order is on its way. TEXT;echo "\n";Hi Ada,
Order #1042 is on its way. The total was 24.90 euro.You can send it back within 2w.
Thank you!Hi $who, your order #$order is on its way.An html template with a hole for any expression
<?nvs// A piece of a web page, written as an html template. The text between the// backticks is written to the page as it is. Every hole is escaped, so a// value cannot add a tag of its own.
class Shop{ public const string NAME = 'Kettle & Co';
public static function price(int $cents): string { return Core\Str::format('%d.%02d €', $cents / 100, $cents % 100); }
public static function badge(): Core\Html\Markup { return html`<span class="badge">new</span>`; }}
// `{$name}` is a hole for a variable. It prints `<b>Ann</b>`,// so the `<b>` stays text on the page.tainted string $name = '<b>Ann</b>';echo html`<p>Welcome, {$name}</p>`, "\n";
// `<?= ... ?>` is a hole for any expression: a constant, a method call, a// calculation. A `string` result is escaped, so the `&` prints as `&`.echo html`<h1><?= Shop::NAME ?></h1><p class="price"><?= Shop::price(5990) ?></p>`, "\n";
// A result of type `Core\Html\Markup` is written as it is, tags included.bool $isNew = true;echo html`<h2>Teapot <?= $isNew ? Shop::badge() : html`` ?></h2>`, "\n";
// Two fragments are joined with `+`. The result is one `Core\Html\Markup`.Core\Html\Markup $page = html`<header><?= Shop::NAME ?></header>` + html`<main>{$name}</main>`;echo $page, "\n";<p>Welcome, <b>Ann</b></p><h1>Kettle & Co</h1><p class="price">59.90 €</p><h2>Teapot <span class="badge">new</span></h2><header>Kettle & Co</header><main><b>Ann</b></main>Escapes in a double quoted string
<?nvs// Shows the escapes of a double-quoted string, and what is printed for each one.
// `\t` is a tab, `\"` is a quote, `\$` is a dollar sign and `\\` is one backslash.string $who = 'Ada';echo "tab[\t] quote[\"] dollar[\$who] backslash[\\]\n";
// `\101` (octal), `\x41` (hex) and `\u{41}` (a code point) all print `A`.echo "oct[\101] hex[\x41] code point[\u{41}]\n";
// An escape the language does not know keeps its backslash, so this prints `\q`.echo "unknown[\q]\n";
// In braces, any expression that starts with a variable is filled in. This prints `30`.array<int> $n = [10, 20];echo "sum {$n[0] + $n[1]}\n";tab[ ] quote["] dollar[$who] backslash[\]oct[A] hex[A] code point[A]unknown[\q]sum 30Durations
<?nvs// Shows how to write a length of time. A number followed by a unit is a `Core\Time\Duration`.
// Units can follow each other. `1h30m` is one hour and thirty minutes.Core\Time\Duration $wait = 1h30m;echo $wait, ' is ', $wait->toSeconds(), " seconds\n";
// The other units are `ns`, `us`, `ms`, `s`, `d` and `w`.echo 250us->toNanoseconds(), ' ', 1d->toSeconds(), "\n";
// `==` compares two durations by their length. This prints "true".echo $wait == 90m ? 'true' : 'false', "\n";1h30m is 5400 seconds250000 86400trueMarkup joined with a dot
<?nvs// Shows that `.` cannot join markup to a string. Join two markup values with `+`.// This program does not compile.// proof: compile-error
Core\Html\Markup $m = html`<p>x</p>`;string $s = $m . '!';error[E0710]: `Core\Html\Markup` is not text; it is the carrier the HTML sink writes raw --> 07-markup-joined-with-a-dot.nvs:7:13 |7 | string $s = $m . '!'; | ^^ used as a `string` here = help: escaping is not idempotent, so text made out of a `Markup` is escaped a second time at the sink — write the markup to the sink directly, compose it with `+`, or say `Core\Html::toSource($markup, "why")` if the bytes really are what you want
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A float can also be written 1E-2 or 1_000.5. The keywords true, false and null are values too.
A single-quoted string has two escapes: \\ is one backslash and \' is a quote. Every other backslash is printed as it is, so 'a\nb' prints a\nb.
A double-quoted string has the escapes \\, \", \$, \n, \t, \r, \v and \f. It also has an octal escape from \0 to \777, \xHH and \u{HHHH}. An octal or \x escape writes one byte. The bytes of the string must form valid UTF-8, so "\xff" is the error E0431. An escape the language does not know keeps its backslash, so "\q" prints \q.
A string cannot contain the ESC character. This is the error E0011. It is the same for the raw byte and for \e, \x1b, \033 and \u{1b}. To style text in a terminal, use Core\Cli\Text.
In a double-quoted string, $name[key] and $name[0] read one array element. A second [...] after it is text, so "$s[0][1]" prints the element and then [1]. For more, use braces. The expression in braces must start with a variable, and then it can be any expression, such as {$a + $b}. A { with no $ after it is text. "${name}" prints ${name}.
A value in a string is converted the way echo converts it. A number, a bool, a string and null work. bytes, an array and an enum case are the error E0707. An object of a class that does not implement Stringable is the error E0412.
In a heredoc, every line must start with the same spaces as the closing marker. Those spaces are removed. A line with less indentation is the error E0433.
A duration has the units ns, us, ms, s, m, h, d and w. == compares two durations by their length, so 90m == 1h30m is true. Use < and > to put two durations in order.
An anonymous object at the start of a statement must be in parentheses: ({ x: 1 });. Without them it is the error E0117. The same is true for the body of an arrow function.
An html template keeps every byte between the backticks, also the spaces and line breaks. Write a backtick in it as ` \ `. Write \{ for a { that opens no hole. A variable after it is still filled in, so \{$n} prints {, the value and }`.
A brace that is not followed by $ is text. {Page::TITLE} prints as it is written, and the compiler gives the warning W1012. Write <?= Page::TITLE ?> for a constant or a method call.
<?= ... ?> in an html template takes any expression. Spaces around it are allowed. A } inside it is an ordinary brace. The first ?> that is not inside a string or a template closes it. A <?nvs block inside a template is the error E0010. A template is one expression. To repeat markup in a loop, build the fragments in code and join them.
A string in a hole is escaped, also when it is tainted. A Core\Html\Markup in a hole is written as it is. A secret value in a hole is the error E0790. A value with no string form is the error E0707.
+ joins two Core\Html\Markup values. Core\Html::join($parts, $separator) joins a list of them. . with a Core\Html\Markup is the error E0710. The text it would make is escaped a second time when it is printed.
html"..." with double quotes does not compile. The error E0319 says to write it with backticks.
"<p>x</p>" as Core\Html\Markup converts a string that is written directly in the code. Any other string is the error E0417. To turn a computed string into markup, use Core\Html::escape or Core\Html::sanitize.
<<<'TXT', with the marker in single quotes, is a nowdoc. It prints $name as written.
Text and bytes
Text is a string. Data that may not be text is bytes. They are two separate types, and you convert between them with as.
A string is always valid text. Its length is the number of characters a person counts. An accented letter, an emoji or a flag is one character, even when it needs several bytes. There is no $name[0] syntax. Core\Str::at returns one character, and Core\Str::slice returns several.
bytes is for the content of a file, a reply from a network connection or a hash. Its length is the number of bytes. Core\Bytes::slice takes a part of it by byte position.
Good to know: $text as bytes always works. $data as string checks the data first. If the data is not valid text, it throws a RuntimeError.
The examples below show a name measured in characters and in bytes, the first character and a short preview of a title, and uploads sorted into pictures and notes. The last one converts text to bytes and back, and shows the error for data that is not text.
Check a name against two different limits
<?nvs// A display name is limited by what a reader sees; a database column is// limited by what it stores. Those are two different numbers for the same// name, so each one is measured with the type that owns it.
array<string> $names = ['Ann', 'Grüße', "Rene\u{301}e", 'Łukasz Szymański'];
foreach ($names as string $name) { uint $characters = Core\Str::length($name); uint $stored = Core\Bytes::length($name as bytes); echo $name, ': ', $characters, ' characters, ', $stored, " bytes\n";}Ann: 3 characters, 3 bytesGrüße: 5 characters, 7 bytesRenée: 5 characters, 7 bytesŁukasz Szymański: 16 characters, 18 bytesTake the first character and a short preview
<?nvs// The syntax `$title[0]` does not exist, because the first character is not always the first byte.// `Core\Str::at` returns one character, and `Core\Str::slice` returns several.// Both return whole characters. A letter like `ö` is never cut in half.
array<string> $titles = ['Größenwahn', 'Ölzweig', 'Straße am Fluss'];
foreach ($titles as string $title) { string $initial = Core\Str::at($title, 0); string $preview = Core\Str::length($title) > 8 ? Core\Str::slice($title, 0, 8) . '…' : $title; echo $initial, ' ', $preview, "\n";}G Größenwa…Ö ÖlzweigS Straße a…Sort uploads into pictures notes and neither
<?nvs// Files are often sent base64 encoded inside a JSON field.// `Core\Encoding::fromBase64` returns `bytes`, because the data may not be text.// The first bytes show if the file is a PNG picture.// The data becomes a `string` only if it is valid text.
bytes $pngSignature = Core\Encoding::fromHex('89504e47');
array<string> $uploads = [ 'iVBORw0KGgo=', // the first bytes of a PNG 'SGVsbG8sIHdvcmxkIQ==', // a short note 'SGVsbG8s/w==', // a note with one byte that is not text];
foreach ($uploads as string $encoded) { bytes $data = Core\Encoding::fromBase64($encoded); // `as ?string` converts the bytes to a string if they are valid text. // If they are not, the result is `null`. ?string $text = $data as ?string; if (Core\Bytes::startsWith($data, $pngSignature)) { echo 'picture, ', Core\Bytes::length($data), " bytes\n"; } elseif ($text != null) { echo 'note: ', $text, "\n"; } else { echo "neither a picture nor text\n"; }}picture, 8 bytesnote: Hello, world!neither a picture nor textText to bytes and back
<?nvs// Converts text to bytes and back, and shows the error for bytes that are not text.
// `as bytes` gives the UTF-8 bytes of a string. This always works.bytes $name = 'nvs' as bytes;echo Core\Encoding::toHex($name), ' is ', $name as string, "\n";
// `fromHex` gives any bytes, here the two bytes `ff` and `00`.bytes $raw = Core\Encoding::fromHex('ff00');echo Core\Bytes::length($raw), " bytes\n";
// `ff` is not valid UTF-8, so `as string` throws a `RuntimeError`.try { echo $raw as string, "\n";} catch (RuntimeError $e) { echo $e->message, "\n";}6e7673 is nvs2 bytescannot convert `bytes` to `string`: not well-formed UTF-8 at byte 0Details
A string is always valid UTF-8. Its length counts graphemes (what a person counts as one character). "e\u{301}" is an e with a combining accent: it has one grapheme and three bytes.
$s[0] does not compile for a string or for bytes: it is the error E0482. Use Core\Str::slice($s, $i, 1) for a character, or Core\Bytes::slice for a byte position.
You cannot write a bytes value directly in the code. "nvs" as bytes gives the UTF-8 bytes of a string. Core\Encoding::fromHex and Core\Encoding::fromBase64 give any bytes you need.
bytes has no string form of its own. echo $b is the error E0707, so write echo $b as string. If the bytes are not valid UTF-8, $b as string throws a RuntimeError. $b as ?string gives null instead.
== tests whether two strings are equal. "a" < "b" is the error E0715, so use Core\Str::compare to put strings in order. Text has no arithmetic: "3" * 2 is the error E0716. Join two strings with ., or convert a string to a number with as int or as float.
Do and don’t
Section titled “Do and don’t”- Do use double quotes and interpolation for short messages.
- Do use
Core\Strmethods to measure and cut a string. - Don’t do arithmetic on a string.
"3" * 2does not compile. Convert it first:"3" as int. - Don’t keep binary data in a
string. Usebytes.
