Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a line break at the mid point of a string split by whitespace

Tags:

string

text

php

Using php: How can I insert a line break at the whitespace that falls in the relative middle of string? Or in other words, how do I count the words in a sentence and then put a line break in the sentence at the halfway point?

The idea is to avoid widows (abandoned words) on the second line of blog article titles by essentially cutting each title in half and putting it on two line if the title takes up more than one line.

Thanks in advance.

Update: Hi All, I realized I needed the preg_split function to split the title by whitespaces. Sorry if that part was not clear in the question. I modified Asaph'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. Cheers.

like image 237
Brandon Brown Avatar asked May 04 '12 18:05

Brandon Brown


1 Answers

Use PHP's wordwrap() function. You can use your string's length divided by 2 as the 2nd argument. Here is an example:

<?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;
?>

It outputs:

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

If you want HTML output, you can use the optional 3rd argument to specify the break characters. Like this:

$wrapped = wordwrap($sentence, $width, '<br />');
like image 172
Asaph Avatar answered Oct 23 '22 03:10

Asaph