Split Strings in Half (Word-Aware) with PHP

前端 未结 7 1599
醉话见心
醉话见心 2020-12-11 02:06

I\'m trying to split strings in half, and it should not split in the middle of a word.

So far I came up with the following which is 99% working :

$te         


        
7条回答
  •  生来不讨喜
    2020-12-11 02:47

    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.

    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.

    Give less to string1 on split word

    $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"
    

    Give more to string1 on split word

    $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"
    

提交回复
热议问题