为什么我的PHP程序不起作用?

时间:2017-05-19 07:16:29

标签: php html

我是PHP的初学者,我编写了一个代码来证明Google Chrome浏览器中的一段文字是合理的。这是代码:

<!DOCTYPE html>
<html>
<head>
    <title>Text Justification with PHP</title>
    <link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<h1>Text Justification with PHP</h1>
<?php
$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;
$lineLength = 40;
$myText = str_replace("\r\n", "\n", $myText);
$myTextJustified = "";
$numLines = substr_count($myText, "\n");
$startOfLine = 0;
for ($i = 0; $i < $numLines; $i++){
    $originalLineLength = strpos($myText, "\n", $startOfLine) - $startOfLine;
    $justifiedLine = substr($myText, $startOfLine, $originalLineLength);
    $justifiedLineLength = $originalLineLength;

    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++;
            }
        }
    }
    $myTextJustified .= "$justifiedLine\n";
    $startOfLine += $originalLineLength + 1;
}
?>
<h3>Original Text:</h3>
<p><?php echo str_replace("\n", "<br>", $myText); ?></p><br><br>
<h3>Justified Text:</h3>
<p><?php echo str_replace("\n", "<br>", $myTextJustified); ?></p>
</body>
</html>

但是文本没有合理性,我的段落完全相同。这与浏览器兼容性有关吗?有人能告诉我吗?感谢您的关注。

1 个答案:

答案 0 :(得分:2)

您试图通过在单词之间插入空格来证明文本的合理性。

HTML是一种语言,它指定文档的结构,而不是其格式。根据设计,任何呈现HTML的程序都会用一个空格替换两个或多个空白字符(空格,换行符,制表符)的序列。

首先,看一下浏览器收到的HTML文档的来源(使用Ctrl-U或菜单中的Developer Tools命令)。这样,您可以检查算法是否产生了您期望的结果。

为了强制浏览器根据需要渲染空格,一个简单的解决方案是使用non-breaking spaces代替。在HTML中,不间断空格被编码为&npsp;

但是,正如其名称所示,不间断的空格不允许浏览器在该点断开(如果需要)。

除了您的代码是对齐算法的编程练习之外,在HTML(+ CSS)中,证明文本对齐的标准方法是在段落上使用text-align: justify; CSS属性:

<p style="text-align: justify;">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.</p>

这就是它的工作原理:https://codepen.io/anon/pen/JNmMwQ