問題描述
我正在嘗試將字符串分成兩半,它不應該在單詞中間分開.
I'm trying to split strings in half, and it should not split in the middle of a word.
到目前為止,我想出了以下 99% 的工作:
So far I came up with the following which is 99% working :
$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";
$half = (int)ceil(count($words = str_word_count($text, 1)) / 2);
$string1 = implode(' ', array_slice($words, 0, $half));
$string2 = implode(' ', array_slice($words, $half));
這確實有效,根據字符串中的單詞數將任何字符串正確地分成兩半.但是,它正在刪除字符串中的任何符號,例如對于上面的示例,它將輸出:
This does work, correctly splitting any string in half according to the number of words in the string. However, it is removing any symbols in the string, for example for the above example it would output :
The Quick Brown Fox Jumped
Over The Lazy Dog
我需要在拆分后保留字符串中的所有符號,例如 : 和/.我不明白為什么當前的代碼要刪除符號...如果您能提供替代方法或修復此方法以不刪除符號,將不勝感激:)
I need to keep all the symbols like : and / in the string after being split. I don't understand why the current code is removing the symbols... If you can provide an alternative method or fix this method to not remove symbols, it would be greatly appreciated :)
推薦答案
在查看您的示例輸出時,我注意到我們所有的示例都關閉了,如果字符串的中間在一個單詞內,我們將減少給 string1然后給予更多.
Upon looking at your example output, I noticed all our examples are off, we're giving less to string1 if the middle of the string is inside a word rather then giving more.
例如The Quick : Brown Fox Jumped Over The Lazy/Dog
的中間是The Quick : Brown Fox Ju
,它在一個詞的中間,這個第一個示例為 string2 提供了拆分詞;下面的例子給出了 string1 的分割詞.
For example the middle of The Quick : Brown Fox Jumped Over The Lazy / Dog
is The Quick : Brown Fox Ju
which is in the middle of a word, this first example gives string2 the split word; the bottom example gives string1 the split word.
在拆分詞上給 string1 少
$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";
$middle = strrpos(substr($text, 0, floor(strlen($text) / 2)), ' ') + 1;
$string1 = substr($text, 0, $middle); // "The Quick : Brown Fox "
$string2 = substr($text, $middle); // "Jumped Over The Lazy / Dog"
在拆分詞上給 string1 更多
$text = "The Quick : Brown Fox Jumped Over The Lazy / Dog";
$splitstring1 = substr($text, 0, floor(strlen($text) / 2));
$splitstring2 = substr($text, floor(strlen($text) / 2));
if (substr($splitstring1, 0, -1) != ' ' AND substr($splitstring2, 0, 1) != ' ')
{
$middle = strlen($splitstring1) + strpos($splitstring2, ' ') + 1;
}
else
{
$middle = strrpos(substr($text, 0, floor(strlen($text) / 2)), ' ') + 1;
}
$string1 = substr($text, 0, $middle); // "The Quick : Brown Fox Jumped "
$string2 = substr($text, $middle); // "Over The Lazy / Dog"
這篇關于使用 PHP 將字符串分成兩半(字識別)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!