Select the first 90 characters from the content

I am modifying a piece of code, the essence is to pick the first 90 characters from the body of a post. I have managed to get the text including some punctuation characters.

My problem is that I do not know how to get the 90 characters NOT to ignore newline. I want it to terminate once it encounters a line break. As it is now, it doesn’t respect it and so ends up adding content from another line/paragraph.

Read More

This is the code I am using –

$title_data = substr($postdata,0,90);
$title_data = preg_replace("/[^w#&,":; ]/",'', strip_tags($title_data));
$data['post_title'] = "F. Y. I - " . $title_data . " ...";

Related posts

Leave a Reply

3 comments

  1. The right first step you do the preg_replace(), then you put that value to substr() param.

    $title_data = preg_replace("/[^w#&,":; ]/",'', strip_tags($postdata));
    $data = substr($title_data,0,90);
    $data['post_title'] = "F. Y. I - " . $data . " ...";
    
  2. Here’s my to cents… It also makes sure words aren’t truncated.

    // Break the string after the first paragraph (if any)
    $parts = explode('</p>', $postdata);
    
    // Remove all HTML from the first element (which contain the full text if no paragraph exists)
    $excerpt = strip_tags($parts[0]);
    
    $ending = '...';
    
    if (strlen($excerpt) > 90) {
        // Check where the last space is, so we don't truncate any words.
        $excerpt = substr($excerpt, 0, 90 - strlen($ending));
        $excerpt = substr($excerpt, 0, strrpos($excerpt, ' '));
    } 
    
    
    // Return the new string
    $data['post_title'] = "F. Y. I - " . $excerpt . $ending;
    
  3. A bit more complicated, but might help to get the result you’re after:

    // Use `wpautop` to work WP's paragraph-adding magic.
    $rawText = wpautop($postdata);
    
    // Remove all the opening `<p>` tags...
    $preSplitContent = str_replace('<p>', '', $rawText);
    // ...and then break into an array using the closing `</p>` tags.
    // (hacky, but this gives you an array where each
    // item is a paragraph/line from your content)
    $splitContent = explode('</p>', $preSplitContent);
    
    // Then run your preg_replace
    // (because `$splitContent[0]` is only the first
    // line of your text, you won't include any content
    // from the other lines)
    $firstLine = preg_replace("/[^w#&,":; ]/",'', strip_tags($splitContent[0]));
    
    // Then trim the result down to the first 90 characters
    $finalText = substr($firstLine,0,90);
    
    $data['post_title'] = "F. Y. I - " . $finalText . " ...";