Jump to content

Trimming strings


alexpeterson

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.