【发布时间】:2020-02-23 18:51:19
【问题描述】:
我应该生成一个带有文件名的网格。文件名的网格列是 45 个符号宽度。文件名中的单词可以用空格(“”)或下划线(“_”)分隔,也可以是一个长单词。
例如:
我的第一个文件,里面有很多有趣的内容。docx
(58 symbols)My_second_file 也是与_a_lot_of_content_and_pictures.zip
(61 symbols)我可爱的短文件.odt
(24 symbols)SplitMeWhereverYouWantButDontSortMeOutHoweverYouCanNeverNever.pdf
(65 symbols)
想要的结果是:
|=========================================|
| My fist file with a lot of interesting |
| content in it.docx |
-------------------------------------------
| My_second_file is also with_a_lot_of_ |
| content_and_pictures.zip |
-------------------------------------------
| My lovely short file.odt |
-------------------------------------------
| SplitMeWhereverYouWantButDontSortMeOutH |
| oweverYouCanNeverNever.pdf |
我的第一个想法是使用wordwrap ($fileName, 40),但这仅适用于第一个文件名。这不会添加所需的格式。所以我只弄清楚如何使用 str_pad 处理短 40 个符号的文件。
所以我现在的代码草案是:
$grid = “|”.str_repeat(“=“,40).”|\r\n”;
foreach($filenames as $filename) {
$grid .= “|”.str_pad($filename, 40).”|\r\n”;
$grid .= “|”.str_repeat(“-“,40).”|\r\n”;
}
我不知道如何拆分其他较长的文件。
【问题讨论】:
-
@WiktorStribiżew 你是说PHP代码的例子吗?
-
@WiktorStribiżew 啊,好的。固定
-
好吧,这个
_有点混乱,您似乎想删除空格,但将_保留在上一行的末尾。试试preg_replace('~\s*([^\s_]{39}|.{1,39}(?![^\s_])_*)~s', "$1$2\n", $filename),见PHP demo -
@WiktorStribiżew 这似乎工作得很好!然后我可能会
explode它通过“\n” 并且能够为每一行添加正确的格式(str_pad 和“|”)。您想将其发布为答案吗?