ループarray_reverse
の直前に使用foreach
この関数を使用すると、ループを実行する前に配列array_reverse
を逆にすることができます(なぜ? ではなく、とにかくすべてを調べているように見えます)。$message
for
foreach
このコードの単純なリファクタリング
まず第一に、コードは 2 つの関数である必要があります。これは、まったく関連のない 2 つのタスクを実行しているためです。両方を呼び出すラッパー関数が必要な場合は、必ずそうしてください。
入力テキストをツイートに分割する関数は次のとおりです。
// This function will separate an arbitrary length input text into 137 or less chatracter tweets.
function separateTextIntoTweets($input, $reversed = true) {
// Remove line breaks from input, then allocate to an array
$input = trim(preg_replace('/\s\s+/', ' ', $input));
$text_arr = explode(" ", $input);
$tweets = array();
$tweet = "";
// Using a while loop, we can check the length of $text_arr on each iteration
while(!empty($text_arr)) {
// Take first word out of the array
$word = array_shift($text_arr);
if(strlen($tweet) + strlen($word) < 137) { // Fits in this tweet
$tweet .= " $word";
} else { // Does not fit in this tweet
$tweets[] = trim($tweet);
$tweet = $word;
}
}
// If there's a leftover tweet, add it to the array
if(!empty($tweet)) $tweets[] = $tweet;
// Return tweets in the reversed order unless $reversed is false
return ($reversed) ? array_reverse($tweets) : $tweets;
}
これのライブデモンストレーション。
そして、これはマルチパートツイートを送信する関数で、配列内の最後のツイートを除くすべてに「...」を追加します:
// This function sends tweets, appending '...' to continue
function sendTweets($tweets) {
foreach($tweets as &$tweet) {
$status = new Tweet();
$tweet = ($tweet == end($tweets)) ? $tweet : $tweet . "...";
$status->set($tweet);
}
}
sendTweets
目的の結果を得るために の出力を直接呼び出すことができるように、これを設計しましseparateTextIntoTweets
た。
あまり標準的でない機能の説明
必要に応じて、コードのあまり明白でない部分の説明:
&$tweet
- Passes $tweet by reference so that it can be modified to append '...'
$tweet = ($tweet == end($tweets)) ? $tweet : $tweet . "..."
- Conditional ternary operator, this is shorthand for:
if($tweet == end($message)) {
$tweet = $tweet;
} else {
$tweet = $tweet . "...";
}
end($tweets)
- Refers to the last element in the $tweets array
array_shift
- Removes and returns the first element from an array
strlen
- Length of a string
preg_replace('/\s\s+/', ' ', $input)
- Replaces excess whitespace, and newlines, with a single space.