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.