Ad Escaping characters while formatting
To escape special characters, such as `\n`, `\t`, etc., is needed usage of multiple escaping to avoid expanding the formatting key or special character itself.
In my case I needed a new line sequence `\n` to be printed in the output as is i.e. as a plain text with backslash and letter n.
In the example bellow there are used letters `Y`, `n`, `W` that without escaping are recognized as format character representing full year (`Y`), month number(`n`) and week number (`W`).
<?php
$now = new DateTime();
echo $now->format('Y\\\\\nW');
$formats = [
'YnW', 'Y\nW', 'Y\\nW', 'Y\\\nW', 'Y\\\\nW', 'Y\\\\\nW', 'Y\\\\\\nW', 'Y\\\\\\\nW', 'Y\\\\\\\\nW', 'Y\\\\\\\\\nW', 'Y\\\\\\\\\\nW', ];
foreach($formats as $key => $format){
echo PHP_EOL . $key . '. format: '. var_export($format, true) ."\t".' output: '. $now->format($format);
}
?>
Prints something like:
0. format: 'YnW' output: 20251041
1. format: 'Y\\nW' output: 2025n41
2. format: 'Y\\nW' output: 2025n41
3. format: 'Y\\\\nW' output: 2025\1041
4. format: 'Y\\\\nW' output: 2025\1041
5. format: 'Y\\\\\\nW' output: 2025\n41
6. format: 'Y\\\\\\nW' output: 2025\n41
7. format: 'Y\\\\\\\\nW' output: 2025\\1041
8. format: 'Y\\\\\\\\nW' output: 2025\\1041
9. format: 'Y\\\\\\\\\\nW' output: 2025\\n41
10. format: 'Y\\\\\\\\\\nW' output: 2025\\n41