【问题标题】:PHP: Split text string into substrings not longer than 40 symbols without word breaks (spaces or “_” between words)PHP:将文本字符串拆分为不超过 40 个符号的子字符串,没有分词(单词之间的空格或“_”)
【发布时间】: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 和“|”)。您想将其发布为答案吗?

标签: php regex string


【解决方案1】:

你可以使用

preg_replace('~\s*([^\s_]{39}|.{1,39}(?![^\s_])_*)~s', "$1\n", $filename)

查看PHP demoregex demo

模式详情

  • \s* - 0+ 个空格(将被删除)
  • ([^\s_]{39}|.{1,39}(?![^\s_])_*) - 第 1 组:
    • [^\s_]{39} - 除空格和下划线以外的 39 个字符
    • | - 或
    • .{1,39} - 尽可能多的 1 到 39 个字符,但
    • (?![^\s_]) - 不紧跟除空格或 _ 以外的字符
    • _* - 0 个或多个下划线。

s 修饰符允许 . 匹配任何字符,包括换行字符。

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 2011-06-12
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    相关资源
    最近更新 更多