title: Extract paragraph (>800 chars) from text files
body: <p>I need to extract rather long excerpts from text files. For this reason I decided to extract the first encountered paragraph, which is >800 characters long, and cut it to 800 chars, adding "..." in the end. If such paragraph is not found – then step down to 700, 600, 500.</p>
  
  <p>Please help me to improve this PHP code.
  Or, if you know the bash-solution – would be nice too. Thanks in advance.</p>
  
  <pre><code>if ($text != false &amp;&amp; $text != '') {
      preg_match('#^(.{50,100})(\s+)#s', $text, $aSubject);
      preg_match('#([^\n]{400,800})(.*)#', $text, $aAnnotation);
      $text = preg_replace('#([\n\r\t\s]+)#s', " ", $text);
      // $text = preg_replace('#([\w|\s]+)#s', "\1", $text);
      $wordcount = count(explode(" ", $text));
      // if (isset($aAnnotation[1]) &amp;&amp; isset($aSubject[1])) {
      if (isset($aAnnotation[1])) {
          $sAnnotation = preg_replace('#(\s{2,100})#', ' ', $aAnnotation[1]);
          $stmt = $hDB-&gt;prepare("INSERT INTO {$_S['tableText']} (filename, text) values (?, ?)");
          $stmt-&gt;execute([$aFilename[1], trim($text)]);
          // $stmt = $hDB-&gt;prepare("INSERT INTO {$_S['tableKeywords']} (filename, subject, annotation) values (?, ?, ?)");
          // $stmt-&gt;execute([$File, $aSubject[1], $sAnnotation]);
          $stmt = $hDB-&gt;prepare("INSERT INTO {$_S['tableKeywords']} (filename, annotation, wordcount) values (?, ?, ?)");
          $stmt-&gt;execute([$aFilename[1], $sAnnotation, $wordcount]);
          $aExts[$aFilename[3]] = (isset($aExts[$aFilename[3]])) ? $aExts[$aFilename[3]] + 1 : 1;
          // unlink($_S['textDir'] . '/' . $File);
      }
  }
  </code></pre>