2017-05-19 12 views
-2

私はPHPの初心者です。私は、Google Chromeブラウザのテキストを正当化するコードを書いています。私のPHPプログラムが動作しないのはなぜですか?

<!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

なぜCSSを使用しないのですか? –

答えて

2

単語間にスペースを挿入してテキストを正当化しようとしています。

HTMLは、書式ではなくドキュメントの構造を指定する言語です。設計上、HTMLをレンダリングするプログラムは、2つ以上の空白文字(スペース、改行、タブ)のシーケンスを単一のスペースで置き換えます。

まず、HTMLドキュメントのソースをブラウザーで受信したときに見てください(Ctrl-Uまたはメニューから開発者ツールコマンドを使用してください)。この方法で、あなたのアルゴリズムがあなたが期待する結果を生み出すかどうかを確認することができます。

ブラウザが空白をレンダリングするように強制するには、代わりに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

+0

ありがとう –

関連する問題