How to add a line break in the middle of a dot separated by spaces

Using php: how can I insert a line break in spaces that fall in the relative middle of the line? Or, in other words, how do I count words in a sentence and then put a line break in a sentence halfway?

The idea is to avoid the widows (left words) in the second line of the headings of blog posts, essentially cutting each headline in half and putting it in two lines if the heading is longer than one line.

Thanks in advance.

Update: Hello everyone, I realized that I need the preg_split function to split the title into spaces. Sorry if this part was not clear in the question. I modified Asaf's answer and used this:

$title_length = strlen($title);
if($title_length > 30){
    $split = preg_split('/ /', $title, null, PREG_SPLIT_NO_EMPTY);
    $split_at = ceil(count($split) / 2);
    echo $split_at;
    $broken_title = '';
    $broken = false;
    foreach($split as $word_pos => $word){
        if($word_pos == $split_at  && $broken == false){
            $broken_title.= '<br />'."\n";
            $broken = true;
        }
        $broken_title .= $word." ";
    }
    $title = $broken_title;
}   

I'm new to SO and I'm blown away by the power of the community. Greetings.

+5
2

PHP wordwrap(). , 2, . :

<?php
$sentence = 'This is a long sentence that I would like to break up into smaller pieces.';
$width = strlen($sentence)/2;
$wrapped = wordwrap($sentence, $width);
echo $wrapped;
?>

:

This is a long sentence that I would
like to break up into smaller pieces.

HTML, , . :

$wrapped = wordwrap($sentence, $width, '<br />');
+5

<?php
$Sentence = 'I will go to the school tomorrow if it is not raining outside and if David is ok with it.';
$Split = explode(' ', $Sentence);

$SplitAt = 0;
foreach($Split as $Word){
    $SplitAt+= strlen($Word)-1;
    if($SplitAt >= strlen($Sentence)){
        break;
    }
}

$NewSentence = wordwrap($Sentence, $SplitAt, '<br />' . PHP_EOL);


echo $NewSentence;
?>

:

, < br/ > \n
     , .

EDIT: PHP_EOL html < br/ >

0

All Articles