3v4l.org

run code in 500+ PHP versions simultaneously
<?php // If chunk_len is negative, offset 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; } echo "Merry Xmas!\n"; for( $len = 0; $len < 24; ++$len ){ $chunks = str_split_offset( str_repeat('X', $len ), (int)( $len / 3 ), (int)( $len / 2 ), ' '); echo str_pad("/{$chunks}\\", 100, ' ', STR_PAD_BOTH ), "\n"; } echo "\nGroup the digits of powers of two\n"; for( $bits = 0; $bits < 63; ++$bits ){ $chunks = str_split_offset( 1 << $bits, -3, 0, '_'); echo str_pad( $bits, 2, ' ', STR_PAD_LEFT ), str_pad( $chunks, 26, ' ', STR_PAD_LEFT ), "\n"; } $str = '1234567890123'; $chunk_len = 5; echo "\nOffset from left\n"; for( $offset = -$chunk_len * 2; $offset <= $chunk_len * 2; ++$offset ){ $chunks = str_split_offset( $str, $chunk_len, $offset, ' '); echo str_pad( $offset, 3, ' ', STR_PAD_LEFT ), " |{$chunks}|\n"; } echo "\nOffset from right\n"; for( $offset = -$chunk_len * 2; $offset <= $chunk_len * 2; ++$offset ){ $chunks = str_split_offset( $str, -$chunk_len, $offset, ' '); echo str_pad( $offset, 3, ' ', STR_PAD_LEFT ), str_pad("|{$chunks}|\n", 20, ' ', STR_PAD_LEFT ); }

preferences:
15.63 ms | 499 KiB | 6 Q