note 128464 added to function.str-split
| From: | biziclop at main dot php dot net | Date: | Mon, 08 May 2023 13:16:42 +0000 |
| Subject: | note 128464 added to function.str-split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220419@lists.php.net to get a copy of this message | ||
Sometimes it can be necessary to split_str by start chunking from the end of the string or shift the
split positions by some amount, so I wrote a function that makes it possible:
<?php
echo str_split_offset( decbin(12345), -4, 0, ' ');
// Prints '11 0000 0011 1001'
echo str_split_offset('1234567890', -3, 0, '_');
// Prints 1_234_567_890
echo str_split_offset('1000000000000USD', -6, 3, ' ');
// Prints '1 000000 000000 USD'
// More demos: https://3v4l.org/7tf69
// If chunk_len is negative, chunking starts from the end of the string
function str_split_offset( $str, $chunk_len = 1, $offset = 0, $joiner = null ){
$len = strlen( $str );
if( $chunk_len < 0 ){
$chunk_len = -$chunk_len;
$offset = $len - $offset;
}else if( ! $chunk_len ){
$chunk_len = 1;
}
$offset = ( $offset % $chunk_len + $chunk_len ) % $chunk_len;
if( $offset === 0 ){
$a = str_split( $str, $chunk_len );
}else{
/**/ // You can choose from two workhorses:
$str = str_repeat(' ', $chunk_len - $offset ) . $str;
$a = str_split( $str, $chunk_len );
$a[0] = substr( $a[0], $chunk_len - $offset );
/*/
$a = array( substr( $str, 0, $offset ));
for( ; $offset < $len; $offset += $chunk_len )
$a[] = substr( $str, $offset, $chunk_len );
/**/
}
return $joiner !== null ? implode( $joiner, $a ) : $a;
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.130 (proxied: 92.249.199.186)
----
Manual Page -- https://php.net/manual/en/function.str-split.php
Edit -- https://main.php.net/note/edit/128464
Del: integrated -- https://main.php.net/note/delete/128464/integrated
Del: useless -- https://main.php.net/note/delete/128464/useless
Del: bad code -- https://main.php.net/note/delete/128464/bad+code
Del: spam -- https://main.php.net/note/delete/128464/spam
Del: non-english -- https://main.php.net/note/delete/128464/non-english
Del: in docs -- https://main.php.net/note/delete/128464/in+docs
Del: other reasons-- https://main.php.net/note/delete/128464
Reject -- https://main.php.net/note/reject/128464
Search -- https://main.php.net/manage/user-notes.php