title: How do I add a line break at the mid point of a string split by whitespace
body: <p>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?</p>
  
  <p>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.</p>
  
  <p>Thanks in advance.</p>
  
  <p>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:</p>
  
  <pre><code>$title_length = strlen($title);
  if($title_length &gt; 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 =&gt; $word){
          if($word_pos == $split_at  &amp;&amp; $broken == false){
              $broken_title.= '&lt;br /&gt;'."\n";
              $broken = true;
          }
          $broken_title .= $word." ";
      }
      $title = $broken_title;
  }   
  </code></pre>
  
  <p>I'm new to SO and I'm blown away by the power of the community. Cheers.</p>