在排序期间保留线路断裂



这不一定是PHP特定的,尽管我正在使用PHP。我想我正在寻找一种创意解决方案。

说我在文本中有一个用额外的新行分开的术语列表,例如:

Cookie
Apple
Banana

我想对这些条款进行排序并在页面提交后显示它们,以使结果看起来像:

Apple
Banana
Cookie

不喜欢

Apple
Banana
Cookie

(将在两条空白行之前)

有人对如何可能会有任何建议?

对不起,我应该更加清楚。TextArea中的列表由用户输入,因此它可能包含额外的新线。

如果总是有两个新线,那么分裂,排序和加入就像:

$result = explode("nn", $text);
sort($result);
$result = implode("nn", $result);

如果可能是一个或多个新线:

preg_match_all("/^(.+$)(n+)?/m", $text, $matches);
sort($matches[1]);
$result = '';
foreach($matches[1] as $key => $val) {
    $result .= $val . $matches[2][$key];
}
  • 匹配所有行文本$matches[1]和终止新线(如果有)$matches[2]
  • 对行文本数组$matches[1]
  • 进行排序
  • 循环行文本数组$matches[1]并添加相应的新线(如果有)$matches[2]

包括newlines,每个数组都应具有奇数的元素,因此数组的整数值。lengthth/2始终应产生newlines的数量,并且还应产生索引第一个单词以0索引语言。

对于数组中的单词数(即,从数组.length/2到数组的末端,独家),您可以打印单词并打印单词索引中的任何内容 - array.lengths/2,这应该是新线,直到最后一个字。如果索引是最后一句话,则不应在此后打印新线。

您可以首先使用php内置的 explode()函数内置的php来完成此操作来自有实际文本的行的新行,然后是空白行)作为要爆炸的定界符。对数组进行排序,然后从中重新构造字符串,手动添加新行。

下面的功能演示了如何实现这一目标,可以直接适用于您的需求,否则指导您朝正确的方向指导:

function sort_list_with_line_breaks($list_string){
  $return_list = '';
  // Break the string on newline followed by blank line into array
  $list_array = explode("nn", $list_string);
  // Apply your sorting
  sort($list_array);
  // Reconstruct string
  $count = 0;
  foreach($list_array as $string){
      if($count == count($list_array)){ break; }
      if($count != 0){ $return_list .= "nn"; }
      $return_list .= $string;
      $count++;
  }
  return $return_list;
} 

最新更新