note 123431 added to function.sprintf

From: Date: Thu, 13 Dec 2018 14:26:06 +0000
Subject: note 123431 added to function.sprintf
Groups: php.notes 
Request: Send a blank email to php-notes+get-209893@lists.php.net to get a copy of this message
I have written a wrapper for sprintf. Add a new %S (upper case s) where the number indicates the number of characters and not bytes. This is useful for formatting utf-8 strings. <?php function SacSprintf( $format) { $argv = func_get_args() ; array_shift($argv) ; $offset = 0; $i = 0; while( preg_match("^A%[+-]*[.]*([0-9.]*)([a-z])^Ai", $format, $match, PREG_OFFSET_CAPTURE, $offset)) { if( $match[2][0] == 'S') { if( $match[1][0] != '') { $t1 = explode('.', $match[1][0]); $t1[0] = intval($t1[0]) + strlen($argv[$i]) - strlen(utf8_decode($argv[$i])); $l1 = strlen($match[1][0]); $t2 = implode('.', $t1); $l2 = strlen($t2) - $l1; $format = substr_replace( $format, $t2, $match[1][1], strlen($match[1][0])); $offset += $l2; $match[2][1] += $l2; } $format[$match[2][1]] = 's'; } $offset += $match[2][1]; $i++; } return vsprintf($format, $argv) ; } echo "<pre>\n"; echo " 1234567890123456789012345678901234567890\n"; echo sprintf("Hola, %-20s is my name\n", "José Luis jiménez"); echo SacSprintf("Hola, %-20S is my name\n", "José Luis jiménez"); echo "</pre>\n"; ?> The output will be: 1234567890123456789012345678901234567890 Hola, José Luis jiménez is my name Hola, José Luis jiménez is my name ---- Server IP: 208.43.231.9 Probable Submitter: 2a01:6900:0:1001:9e3:2b1f:4172:8d49 ---- Manual Page -- http://php.net/manual/en/function.sprintf.php Edit -- https://master.php.net/note/edit/123431 Del: integrated -- https://master.php.net/note/delete/123431/integrated Del: useless -- https://master.php.net/note/delete/123431/useless Del: bad code -- https://master.php.net/note/delete/123431/bad+code Del: spam -- https://master.php.net/note/delete/123431/spam Del: non-english -- https://master.php.net/note/delete/123431/non-english Del: in docs -- https://master.php.net/note/delete/123431/in+docs Del: other reasons-- https://master.php.net/note/delete/123431 Reject -- https://master.php.net/note/reject/123431 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#209893) next »