<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Justifying Lines of Text</title>
<link rel="stylesheet" type="text/css" href="common.css" />
<style>
pre {font-family: Courier, monospace;}
</style>
</head>
<body>
<h1>Justifying Lines of Text</h1>
<?php
// The text to justify
$myText = <<<END_TEXT
But think not that this famous town has
only harpooneers, cannibals, and
bumpkins to show her visitors. Not at
all. Still New Bedford is a queer place.
Had it not been for us whalemen, that
tract of land would this day perhaps
have been in as howling condition as the
coast of Labrador.
END_TEXT;
$myText = str_replace( "\r\n", "\n", $myText );
$lineLength = 40; // The desired line length
$myTextJustified = "";
$numLines = substr_count( $myText, "\n" );
$startOfLine = 0;
// Move through each line in turn
for ( $i=0; $i < $numLines; $i++ ) {
$originalLineLength = strpos( $myText, "\n", $startOfLine ) - $startOfLine;
$justifiedLine = substr( $myText, $startOfLine, $originalLineLength );
$justifiedLineLength = $originalLineLength;
// Keep adding spaces between words until the desired
// line length is reached
while ( $i < $numLines - 1 && $justifiedLineLength < $lineLength ) {
for ( $j=0; $j < $justifiedLineLength; $j++ ) {
if ( $justifiedLineLength < $lineLength && $justifiedLine[$j] == " " ) {
$justifiedLine = substr_replace( $justifiedLine, " ", $j, 0 );
$justifiedLineLength++;
$j++;
}
}
}
// Add the justified line to the string and move to the
// start of the next line
$myTextJustified .= "$justifiedLine\n";
$startOfLine += $originalLineLength + 1;
本书对上述行的解释是“$ startOfLine指针被移动到 开始下一行(将 1 添加到索引以跳过换行符)。
我的问题是:
新行字符“\ n”不应包含两个字符吗?为了跳过它,我们不应该将2添加到变量$ startOfLine而不是1?
让我们看一个简单的例子:
$myText = "Hello\nworld\n"
strpos ( $myText, "\n", 0); //Returns 5, which is also the length of the first line "Hello"
0+5+1; //Returns 6. It should be the index of the first character of the second line (w). But it's actually the index of the "n" right in front of it
strpos ( $myText, "\n", 6); //Returns 12
12-6 //Returns 6. This should be the length of the second line. But the second line actually contains 5 characters.
但如果我将1更改为2,脚本将无法正常工作。问题是什么?
}
?>
<h2>Original text:</h2>
<pre><?php echo $myText ?></pre>
<h2>Justified text:</h2>
<pre><?php echo $myTextJustified ?></pre>
</body>
</html>
答案 0 :(得分:0)
我认为您正在寻找wordwrap()来证明文本的合理性。
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;
?>
输出:
The quick brown fox<br />
jumped over the lazy<br />
dog.