note 130502 added to datetime.format

From: Date: Thu, 09 Oct 2025 08:33:53 +0000
Subject: note 130502 added to datetime.format
Groups: php.notes 
Request: Send a blank email to php-notes+get-222370@lists.php.net to get a copy of this message
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 /* Escaping new line special character \n to be a plain text */ // Now $now = new DateTime(); // Prints something like: 2025\n41 echo $now->format('Y\\\\\nW'); /* Test of various escaping sequences */ // List of formats in single quotes $formats = [ 'YnW', // 20251041 'Y\nW', // 2025n41 'Y\\nW', // 2025n41 'Y\\\nW', // 2025\1041 'Y\\\\nW', // 2025\1041 'Y\\\\\nW', // 2025\n41 'Y\\\\\\nW', // 2025\n41 'Y\\\\\\\nW', // 2025\\1041 'Y\\\\\\\\nW', // 2025\\1041 'Y\\\\\\\\\nW', // 2025\\n41 'Y\\\\\\\\\\nW', // 2025\\n41 ]; 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 ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.84.18 (proxied: 158.88.8.6) ---- Manual Page -- https://php.net/manual/en/datetime.format.php Edit -- https://main.php.net/note/edit/130502 Del: integrated -- https://main.php.net/note/delete/130502/integrated Del: useless -- https://main.php.net/note/delete/130502/useless Del: bad code -- https://main.php.net/note/delete/130502/bad+code Del: spam -- https://main.php.net/note/delete/130502/spam Del: non-english -- https://main.php.net/note/delete/130502/non-english Del: in docs -- https://main.php.net/note/delete/130502/in+docs Del: other reasons-- https://main.php.net/note/delete/130502 Reject -- https://main.php.net/note/reject/130502 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222370) next »