Re: Re: Substr by words
| From: | Marcus Bointon | Date: | Sun, 30 Oct 2005 12:56:45 +0000 |
| Subject: | Re: Re: Substr by words | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-224842@lists.php.net to get a copy of this message | ||
On 30 Oct 2005, at 06:22, Gustavo Narea wrote:
$replacement = ereg_replace ("^([[:space:]]*[^[:space:][:cntrl:]]+){1,$MaxWords}", "",$MyOriginalString); echo substr( $MyOriginalString, 0, ($replacement) ? -strlen($replacement) : strlen($MyOriginalString));You could get the regex to do the search and the extraction in one go: $MyOriginalString = "This is my original string.\nWhat do you think about this script?"; $MaxWords = 6; // How many words are needed? $matches = array(); if (preg_match("/(\b\w+\b\W*){1,$MaxWords}/", $MyOriginalString, $matches)) {
$result = trim($matches[0]);
echo $result;
}
Marcus
--
Marcus Bointon
Synchromedia Limited: Putting you in the picture
marcus@synchromedia.co.uk | http://www.synchromedia.co.uk