Split Strings in Half (Word-Aware) with PHP

前端 未结 7 1582
醉话见心
醉话见心 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条回答
  •  -上瘾入骨i
    2020-12-11 02:45

    function split_half($string, $center = 0.4) {
            $length2 = strlen($string) * $center;
            $tmp = explode(' ', $string);
            $index = 0; 
            $result = Array('', '');
            foreach($tmp as $word) {
                if(!$index && strlen($result[0]) > $length2) $index++;
                $result[$index] .= $word.' ';
            }
            return $result;
    }
    

    Demo: http://codepad.viper-7.com/I58gcI

提交回复
热议问题