且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 PHP 将字符串分成两半(字识别)

更新时间:2023-02-21 13:32:17

在查看您的示例输出时,我注意到我们所有的示例都关闭了,如果字符串的中间在一个单词内,我们将减少给 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"