Skip to content

Instantly share code, notes, and snippets.

@kawa-
Created February 28, 2017 04:30
Show Gist options
  • Save kawa-/b97c48f4206f691beba13cece69f815d to your computer and use it in GitHub Desktop.
Save kawa-/b97c48f4206f691beba13cece69f815d to your computer and use it in GitHub Desktop.
Twitter等であるような、二行以上の空白行を一行の空白行に変換するメソッド。もっと効率化できる気はする。
/**
* 文字列中の空白行(スペースまじりのものを含む)が二行以上続いたときに一行に変換する
* 例: $tweet = multipleBlankLinesToOneBlankLine($tweet);
*/
function multipleBlankLinesToOneBlankLine($str) {
// 改行コード(\r\n, \r, \n) を全て \n に統一
$str = str_replace(array('\r\n', '\r', '\n'), '\n', $str);
// 改行コードで分割
$lines = explode("\n", $str);
// 前後の空白を取り除く
$lines = array_map('trim', $lines);
$sum = implode("\n", $lines);
return trim(preg_replace("/\n{2,}/", "\n\n", $sum));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment