Split Strings in Half (Word-Aware) with PHP

前端 未结 7 1591
醉话见心
醉话见心 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

    I know this is an old question, but I have the following piece of code that should do what is needed.

    It by default it splits the string on the first occurrence of a space after the middle. If there are no spaces after the middle, it looks for the last space before the middle.

    function trim_text($input) {
        $middle = ceil(strlen($input) / 2);
        $middle_space = strpos($input, " ", $middle - 1);
    
        if ($middle_space === false) {
            //there is no space later in the string, so get the last sapce before the middle
            $first_half = substr($input, 0, $middle);
            $middle_space = strpos($first_half, " ");
        }
    
        if ($middle_space === false) {
            //the whole string is one long word, split the text exactly in the middle
            $first_half = substr($input, 0, $middle);
            $second_half = substr($input, $middle);
        }
        else {
            $first_half = substr($input, 0, $middle_space);
            $second_half = substr($input, $middle_space);
        }
            return array(trim($first_half), trim($second_half));
    }
    

    These are examples:

    Example 1:

    "WWWWWWWWWW WWWWWWWWWW WWWWWWWWWW WWWWWWWWWW"

    Is split as

    "WWWWWWWWWW WWWWWWWWWW"

    "WWWWWWWWWW WWWWWWWWWW"

    Example 2:

    "WWWWWWWWWWWWWWWWWWWW WWWWWWWWWW WWWWWWWWWW"

    Is split as

    "WWWWWWWWWWWWWWWWWWWW"

    "WWWWWWWWWW WWWWWWWWWW"

    Example 3:

    "WWWWWWWWWW WWWWWWWWWW WWWWWWWWWWWWWWWWWWWW"

    Is split as

    "WWWWWWWWWW WWWWWWWWWW"

    "WWWWWWWWWWWWWWWWWWWW"

    Example 4:

    "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW"

    Is split as

    "WWWWWWWWWWWWWWWWWWWW"

    "WWWWWWWWWWWWWWWWWWWW"

    Hope this can help someone out there :)

提交回复
热议问题