0
<!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指针移动到 开始下一行的下一行的开始(加入到索引跳过。在换行符)
我的问题是:
不应该换行字符“\ 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>
请注意\ n和/ N正确的为\ n – 2013-03-03 19:45:36
感谢指点出来的区别。现在纠正了。 – 2013-03-03 19:50:13
我想我已经找出了这个问题。换行符“\ n”被PHP计算为单个字符。 – 2013-03-04 11:57:50