Jump to content

Recommended Posts

I’m trying to copy the first sentence of a paragraph and save it as a new variable.

 

So I’ve written this long-winded conditional that save each letter one by one until a full stop is reached -

 

<?php /* Trim Item description at first full stop to create title */
        
        if ($row["title"] == NULL) {
        
        $title = '';
        $text = $row["description"];
        $i=0;
        
            while ( $text[$i] != '.' && $i<100) {
                $title .= $text[$i];
                $i++;
            }        
        
?>

 

I’m sure there’s a better way to do this? Is there a PHP function that I could use that creates a variable using the first sentence of a paragraph? I’ve looked into ltrim and rtrim but those don’t really apply in this case, or at least I couldn’t get them to work for me!

 

Thanks!

 

Alex

Link to comment
https://forums.phpfreaks.com/topic/176762-trimming-strings/
Share on other sites

that would work, but if you want to make sure it is always less than 100 characters, you may want to change it up a bit. Someone could make a string with no periods whatsoever, or commas instead of periods, or something stupid. try this

 

function first_sentence($content) {

    $pos = (strpos($content, '.') <= 100) ? strpos($content, '.') : 100;
    return substr($content, 0, $pos+1);
   
}

Link to comment
https://forums.phpfreaks.com/topic/176762-trimming-strings/#findComment-931997
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.