note 70477 modified in function.wordwrap by thiago
| From: | thiago@php.net | Date: | Mon, 18 Aug 2008 17:26:33 +0000 |
| Subject: | note 70477 modified in function.wordwrap by thiago | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-143600@lists.php.net to get a copy of this message | ||
I needed a function to justify the text - not just wrap it. I came up with this:
<?php
function justify($text, $width, $break) {
$marker = "__$%@random#$()__";
// lines is an array of lines containing the word-wrapped text
$wrapped = wordwrap($text, $width, $marker);
$lines = explode($marker, $wrapped);
$result = "";
foreach ($lines as $line_index=>$line) {
$line = trim($line);
$words = explode(" ", $line);
$words = array_map("trim", $words);
$wordcount = count($words);
$wordlength = strlen(implode("", $words));
if (3*$wordlength < 2*$width) {
// don't touch lines shorter than 2/3 * width
continue;
}
$spaces = $width - $wordlength;
$index = 0;
do {
$words[$index] = $words[$index] . " ";
$index = ($index + 1) % ($wordcount - 1);
$spaces--;
} while ($spaces>0);
$lines[$line_index] = implode("", $words);
}
return implode($break, $lines);
}
?>
--was--
I needed a function to justify the text - not just wrap it. I came up with this:
<?
function justify($text, $width, $break) {
$marker = "__$%@random#$()__";
// lines is an array of lines containing the word-wrapped text
$wrapped = wordwrap($text, $width, $marker);
$lines = explode($marker, $wrapped);
$result = "";
foreach ($lines as $line_index=>$line) {
$line = trim($line);
$words = explode(" ", $line);
$words = array_map("trim", $words);
$wordcount = count($words);
$wordlength = strlen(implode("", $words));
if (3*$wordlength < 2*$width) {
// don't touch lines shorter than 2/3 * width
continue;
}
$spaces = $width - $wordlength;
$index = 0;
do {
$words[$index] = $words[$index] . " ";
$index = ($index + 1) % ($wordcount - 1);
$spaces--;
} while ($spaces>0);
$lines[$line_index] = implode("", $words);
}
return implode($break, $lines);
}
?>
http://php.net/manual/en/function.wordwrap.php