Split Strings in Half (Word-Aware) with PHP

前端 未结 7 1610
醉话见心
醉话见心 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 03:00

    I tried using a couple of these answers but didn't get the best results so I thought I would share the solution. I wanted to split my titles in half and display one half white and one half green.

    I ended up combining word count, the length of the text, the half way point and a third of the string. This allowed me to make sure the white section is going to be somewhere between the third way/half way mark.

    I hope it helps someone. Be aware in my code -,& etc would be considered a word - it didn't cause me issues in my testing but I will update this if I find its not working as I hope.

    public function splitTitle($text){
    
        $words = explode(" ",$text);
        $strlen = strlen($text);
        $halfwaymark = ceil($strlen/2);
        $thirdwaymark = ceil($strlen/3);
    
        $wordcount = sizeof($words);
        $halfwords = ceil($wordcount/2);
        $thirdwords = ceil($wordcount/3);
    
        $string1 ='';
        $wordstep = 0;
        $wordlength = 0;
    
    
        while(($wordlength < $wordcount && $wordstep < $halfwords) || $wordlength < $thirdwaymark){
            $string1 .= $words[$wordstep].' ';
            $wordlength = strlen($string1);
            $wordstep++;
        }
    
        $string2 ='';
        $skipspace = 0;
        while(($wordstep < $wordcount)){
            if($skipspace==0) {
                $string2 .= $words[$wordstep];
            } else {
                $string2 .= ' '.$words[$wordstep];
            }
            $skipspace=1;
            $wordstep++;
        }
    
        echo $string1.' '.$string2.'';
    
    }
    

提交回复
热议问题