TOP ▲ itcore TOP プログラムパーツ

uHtmlspecialcharsIndent インデント付きのhtmlspecialchars 行頭の空白を に変換する。 | itcore 2017年

PHP関数

<?php
// インデント付きのhtmlspecialchars 行頭の空白を&nbsp;に変換する。
function uHtmlspecialcharsIndent($text) {
  $a_line = explode("\n", $text); // 行に分割
  $text1 = "";
  for($i2 = 0; $i2 < count($a_line); $i2++) {
    $line = $a_line[$i2];
    for ($i = 0; $i < strlen($line); $i++) {
    $s1 = substr($line, $i, 1);
      if (" " == $s1) {
        $text1 .= "&nbsp;";
      } else if ("\t" == $s1) {
        $text1 .= "&nbsp;&nbsp;&nbsp;&nbsp;";
      } else {
        $text1 .= htmlspecialchars(substr($line, $i)) . "\n";
        break;
      }
    }
    if (count($a_line) -1 != $i2 && 0 == strlen($line)) $text1 .= "\n"; // 最終行以外の空行
  }
  return $text1;
}
?>

単体テスト 実行

<?php include "uHtmlspecialcharsIndent.func"; ?>
<?php
  $text = <<<'EOT'
for ($i = 0; $i < 10; $i++) {
  echo "空白2つ $i";

    echo "タブ1つ $i";
}
EOT;
  $text_disp = nl2br(uHtmlspecialcharsIndent($text));
  echo "$text_disp\n";
?>

<?php include "uJsClose.func"; print(uJsClose()); // 閉じるボタン ?>