Justifying Line of Text in PHP

Introduction

This article explains how to justify a line of text in PHP. I will use some string functions for justifying a line of text. Justifying text means aligning text within a column so that the text is flush with both the left and right margins. Using this article you can justify a paragraph or line of text in a page. For example see the following.

Example

<html>

<head>

<title>Justifying Lines of Text </title>

</head>

<body>

<h1>Justifying Lines of Text </h1>

<?php

$txt = <<<END_TEXT

This article explains adding and

removing Array Elements in PHP.

For this explanation I used some

functions for adding and removing array

elements. These functions are very

important and useful to us in an array

adding a removing.

END_TEXT;

$txt = str_replace("\r\n", "\n", $txt);

$L_length = 40;

$txtJustify = "";

$nofline = substr_count( $txt, "\n" );

$strtofline = 0;

for ( $i=0; $i <$nofline; $i++ )

{

$originallength = strpos( $txt, "\n", $strtofline ) - $strtofline;

$justifyline = substr( $txt, $strtofline, $originallength );

$justifyL_length = $originallength;

while ( $i <$nofline - 1 && $justifyL_length <$L_length )

{

for ( $j=0; $j <$justifyL_length; $j++ )

{

if ( $justifyL_length <$L_length &&$justifyline[$j] == " " )

{

$justifyline = substr_replace( $justifyline, " ", $j, 0 );

$justifyL_length++;

$j++;

}

}

}

$txtJustify .= "$justifyline\n";

$strtofline += $originallength + 1;

}

?>

<h2>Original line of text: </h2>

<pre>

<?php

echo $txt;

?>

</pre>

<h2>Justified line of text: </h2>

<pre>

<?php

echo $txtJustify;

?>

</pre>

</body>

</html>

Output

The first block of text is unjustified text and the second block of text is justified text. Such as:

justify.jpg


Similar Articles