dongzhao4036 2017-11-17 05:26
浏览 84
已采纳

PHP - 在编写固定长度文件时,PHP在第一个文件之后不会将`\ t`作为Tab处理。 为什么?

I am writing a fixed length file using PHP. Each character will have a predefined length. If characters are less than the length then it will insert that number of blank spaces. Each field is separated by TAB.

$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t";
$str3 = str_pad('fifteen',15)."\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);

But TAB is not working as expected.

I can see TAB only after first word (ten). After that there are no more TABs in the output file.

  • 写回答

3条回答 默认 最新

  • dongmao4486 2017-11-17 06:54
    关注

    Your text is rendered correctly.

    A tab does not mean a fixed number of spaces or a printable character. It means "forward the cursor to the next tab stop".

    A tab stop in computers is typically set to every 4 or 8 characters. It's a display issue that will behave differently across various systems and user configurations.

    If you copy your output to your preferred text editor and manually select it, you can see spaces as dots and tabs as lines, as in the examples below:

    Note: your output is the first line ("ten seven fifteen"). I added the second and third lines to illustrate the configured tab length in the text editor.

    If we set tab length to 4: Tab stops set to 4

    The first string contains 10 chars ("t", "e", "n" plus 7 dots), and the next tab stop is at the 12th char. So it's only 2 chars away, that's why your tab character (grey line) is only 2 chars long. The second string has 7 chars, and the next stop is only 1 char away so the tab will have only 1 char. It's the same logic for the third string.

    If we set tab length to 8: Tab stops set to 8

    It follows the same logic, but in this example, the first tab is now bigger because the nearest stop is at position 16, so the tab has 6 chars. The second and third tabs have coincidentally only one char.

    If we set tab length to an odd number like 3: Tab stops set to 3

    This is not common, but it's something possible. In this example, we can see all tabs as multiple spaces. It follows the same logic as explained above, but we can visually see that your code is producing the expected output.

    Notice that I did not change your output in any way. I just played with the editor's configuration.

    If you want a fixed length spacer between your chars, you should use "\s" instead. You can repeat the character like this: "\s\s\s\s", or using str_repeat("\s", 4); or "\s" * 4 if you were using Python.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了