public
Last active

Justify text with php

  • Download Gist
Justify Text.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
------------------------------------------------
<?php
 
ini_set( 'display_errors', 'On' );
error_reporting( E_ALL );
 
$strings = array(
'hello world there ok then' => 'hello world there ok then',
'hello' => ' hello ',
'ok then' => 'ok then',
'this string is almost certainly longer than 48 I think' => 'this string is almost certainly longer than 48 I',
'two words' => 'two words',
'three ok words' => 'three ok words',
'1 2 3 4 5 6 7 8 9' => '1 2 3 4 5 6 7 8 9'
);
 
function justify( $str_in, $desired_length=48 ) {
// Cut off long lines
if ( strlen( $str_in ) > $desired_length ) {
$str_in = current( explode( "\n", wordwrap( $str_in, $desired_length ) ) );
}
// String length
$string_length = strlen( $str_in );
// Number of spaces
$spaces_count = substr_count( $str_in, ' ' );
// Number of total spaces needed
$needed_spaces_count = $desired_length - $string_length + $spaces_count;
// One word, so split spaces in half, ceil it add it to eaither side of the word
// Then take the first 48 chars
if ( $spaces_count === 0 ) {
return str_pad( $str_in, $desired_length, ' ', STR_PAD_BOTH );
}
// How many spaces the string needs per space to have atleast 48 characters
$spaces_per_space = ceil( $needed_spaces_count / $spaces_count );
// Replace all spaces with the neccessary spaces per space
// This string will sometimes be too long
$spaced_string = preg_replace( '~\s+~', str_repeat( ' ', $spaces_per_space ), $str_in );
// Now, some strings will be too long so you need to replace the spaces with one less space until
// the desired amount of characters is reached
//
// This is done with preg_replace callback and the $limit parameter
// Limit replacements to the exact number we need to reach the desired length
return preg_replace_callback(
sprintf( '~\s{%s}~', $spaces_per_space ),
function ( $m ) use( $spaces_per_space ) {
return str_repeat( ' ', $spaces_per_space-1 );
},
$spaced_string,
strlen( $spaced_string ) - $desired_length
);
}
 
 
 
foreach( $strings as $string => $desired_output ) {
echo justify( $string ) . "\n";
}
 
?>
------------------------------------------------
Output
1 2 3 4 5 6 7 8 9
------------------------------------------------
hello world there ok then
hello
ok then
this string is almost certainly longer than 48 I
two words
three ok words
1 2 3 4 5 6 7 8 9
------------------------------------------------

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.