Oihana PHP

setTomlValue.php

Table of Contents

Functions

setTomlValue()  : string
Sets a string value in a TOML document, inside one table only, keeping the rest of the text.

Functions

setTomlValue()

Sets a string value in a TOML document, inside one table only, keeping the rest of the text.

setTomlValue(string $content, string|null $section, string $key, string $value) : string

The replacement is anchored to the requested [section]: a key is only rewritten between that header and the next one. This matters because the same key name often recurs across tables — host or pass under [database], [smtp] and [mysql] — and an unanchored replacement silently overwrites unrelated credentials.

The document is edited as text, not parsed and written back, so nothing else moves: the alignment before = and any trailing comment are kept, and only the quoted value is swapped. When the key is absent, it is added at the end of its section, before the blank lines that close it; when the section itself is absent, it is added at the end of the document. Line endings follow the document's: CRLF when it has one, LF otherwise.

Scope: a key written as a single-line basic ("…") or literal ('…') string. A key holding a number, a boolean, an array or a multi-line string is not recognised, and a new line is added for it instead.

Parameters
$content : string

The TOML document.

$section : string|null

The table name (e.g. database, or app.database), compared without regard to case; null for the root table, above the first header.

$key : string

The key to set.

$value : string

The raw value. It is written as a basic string, escaped by escapeTomlString().

Tags
example
use function oihana\files\toml\setTomlValue;

$toml = "[database]\nhost = \"localhost\" # local\n\n[smtp]\nhost = \"mail\"\n" ;

echo setTomlValue( $toml , 'database' , 'host' , 'db.example.com' ) ;
// [database]
// host = "db.example.com" # local
//
// [smtp]
// host = "mail"
author

Marc Alcaraz (ekameleon)

since
1.7.0
Return values
string —

The updated document.

On this page

Search results