我認爲你不能使用trim,因爲由聯合字符串形成的消息必須保持不變?
這可能會變得複雜。你可以在分割之後做一些測試空間的東西,如果檢測到一個空格,可以提前分割一個字符。相當容易,但如果你有兩個空間在一起呢?還是單字母字?你當然可以用這種方式遞歸地測試,但是最後你可能會得到彼此截然不同的長度分割的字符串。
您需要正確定義您希望它在其中起作用的約束。
請確切說明你想做什麼 - 你想每個部分是平等的?是否在比這更高的優先級之間進行分割,以便長度不重要?
編輯: 然後,如果你不擔心的長度,你可以做這樣的事情[開始與意立碼通過繼續走動的空間來改變長度:
$msg = "hello how are you?are you fine?thanks..";
$parts = split_without_spaces ($msg, 3);
function split_without_spaces ($msg, $parts) {
$parts = str_split(trim($msg), ceil(strlen($msg)/$parts));
/* Used trim above to make sure that there are no spaces at the start
and end of the message, we can't do anything about those spaces */
// Looping to (count($parts) - 1) becaause the last part will not need manipulation
for ($i = 0; $i < (count($parts) - 1) ; $i++) {
$k = $i + 1;
// Checking the last character of the split part and the first of the next part for a space
if (substr($parts[$i], -1) == ' ' || $parts[$k][0] == ' ') {
// If we move characters from the first part to the next:
$num1 = 1;
$len1 = strlen($parts[$i]);
// Searching for the last two consecutive non-space characters
while ($parts[$i][$len1 - $num1] == ' ' || $parts[$i][$len1 - $num1 - 1] == ' ') {
$num1++;
if ($len1 - $num1 - 2 < 0) return false;
}
// If we move characters from the next part to the first:
$num2 = 1;
$len2 = strlen($parts[$k]);
// Searching for the first two consecutive non-space characters
while ($parts[$k][$num2 - 1] == ' ' || $parts[$k][$num2] == ' ') {
$num2++;
if ($num2 >= $len2 - 1) return false;
}
// Compare to see what we can do to move the lowest no of characters
if ($num1 > $num2) {
$parts[$i] .= substr($parts[$k], 0, $num2);
$parts[$k] = substr($parts[$k], -1 * ($len2 - $num2));
}
else {
$parts[$k] = substr($parts[$i], -1 * ($num1)) . $parts[$k];
$parts[$i] = substr($parts[$i], 0, $len1 - $num1);
}
}
}
return ($parts);
}
這照顧多個空間和單字母字符 - 但是如果它們存在,零件的長度可能非常不均勻。在極端情況下它可能會搞砸 - 如果你有一個主要由空格組成的字符串,它可能會返回一個空白部分,或者如果根本無法管理分割,則返回false。請徹底測試一下。
編輯2: 順便說一句,你會更好地改變你的方法在某種程度上:)我嚴重懷疑你實際上必須使用這樣的功能。那麼..我希望你確實有一個堅實的理由,它提出了一些有趣的。
是的,這是可能的,但你需要提出一個關於你想要分割發生的地方的規範。 – tdammers
@tdammers謝謝你的答覆。我可以舉個很簡單的例子嗎?因爲每條消息的長度都不一樣,所以我不知道如何具體分割它。 –
您沒有指定您想要分割的規則。每4個字符?究竟在每個單詞的中間?隨機? – tdammers