Split Strings in Half (Word-Aware) with PHP

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

    function split_half($string){
    $result= array();
    $text = explode(' ', $string);
    $count = count($text);
    $string1 = '';
    $string2 = '';
    if($count > 1){
        if($count % 2 == 0){
            $start = $count/2;
            $end = $count;
            for($i=0; $i<$start;$i++){
                $string1 .= $text[$i]." ";
            }
            for($j=$start; $j<$end;$j++){
                $string2 .= $text[$j]." ";
            }           
        $result[] = $string1;
        $result[] = $string2;
        }
        else{
            $start = round($count/2)-1;
            $end = $count;
            for($i=0; $i<$start;$i++){
                $string1 .= $text[$i]." ";
            }
            for($j=$start; $j<$end;$j++){
                $string2 .= $text[$j]." ";
            }           
        $result[] = $string1;
        $result[] = $string2;
    
        }
    }
    else{
        $result[] = $string;
    }
    return $result;
    }
    

    Use this function to split string into half words..

提交回复
热议问题