alexpeterson Posted October 6, 2009 Share Posted October 6, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/176762-trimming-strings/ Share on other sites More sharing options...
Brandon_R Posted October 6, 2009 Share Posted October 6, 2009 function first_sentence($content) { $pos = strpos($content, '.'); return substr($content, 0, $pos+1); } Source: http://www.electrictoolbox.com/get-first-sentence-php/ Quote Link to comment https://forums.phpfreaks.com/topic/176762-trimming-strings/#findComment-931975 Share on other sites More sharing options...
mikesta707 Posted October 6, 2009 Share Posted October 6, 2009 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); } Quote Link to comment https://forums.phpfreaks.com/topic/176762-trimming-strings/#findComment-931997 Share on other sites More sharing options...
.josh Posted October 6, 2009 Share Posted October 6, 2009 $subject = "blahblahblah"; preg_match('~^[^.]{1,100}~',$subject,$match); echo $match[0]; Quote Link to comment https://forums.phpfreaks.com/topic/176762-trimming-strings/#findComment-931999 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.