我正在尝试将字符串分成两半,它不应该在单词的中间拆分。
到目前为止,我想出了以下 99% 的工作:
$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));
这确实有效,根据字符串中的单词数正确地将任何字符串分成两半。但是,它会删除字符串中的任何符号,例如对于上面的示例,它将输出:
The Quick Brown Fox Jumped
Over The Lazy Dog
拆分后,我需要在字符串中保留所有符号,如 : 和/。我不明白为什么当前代码要删除符号...如果您可以提供替代方法或修复此方法以不删除符号,将不胜感激:)
最佳答案
在查看您的示例输出时,我注意到我们所有的示例都关闭了,如果字符串的中间在一个单词内,我们将减少 string1 而不是提供更多。
例如 The Quick : Brown Fox Jumped Over The Lazy/Dog
的中间是 The Quick : Brown Fox Ju
在一个词的中间,这第一个例子给出了 string2 的分割词;底部的示例为 string1 提供了拆分词。
在分割词上减少 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 - 使用 PHP 将字符串分成两半(Word-Aware),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8187429/