PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Mon Feb 27, 2017 1:43 am

All times are UTC - 5 hours




Post new topic Reply to topic  [ 5 posts ] 
Author Message
PostPosted: Mon Dec 09, 2013 12:10 pm 
Offline
Forum Newbie

Joined: Mon Dec 09, 2013 11:52 am
Posts: 18
Hi
This is m 1st post on this forum, and i want to begin with something useful to contribute.
Here is a small php code that can be used to extract a number of words from text.
Code:
$text = 'Extract the text with first 45 characters from this string.';
$nrw = 10;                         // the number of words we want to extract

$rgxwords = '/([^ ]*[ ]{0,1}){1,'.$nrw.'}/i';            // patern to get a number of words from string
$text = preg_replace('/\s\s+/', ' ', $text);             // replace multiple whitespaces whith single space
$text = trim($text);                                     // to remove whitespace from the beginning and ending

// get the substring
if(preg_match($rgxwords, $text, $mtc)) $txt = $mtc[0];
else $txt = '';

echo $txt;
 


Last edited by requinix on Mon Dec 09, 2013 1:54 pm, edited 1 time in total.
removing advertising


Top
 Profile  
 
PostPosted: Mon Dec 09, 2013 6:16 pm 
Offline
Moderator
User avatar

Joined: Mon Nov 03, 2003 7:13 pm
Posts: 5975
Location: Odessa, Ukraine
Syntax: [ Download ] [ Hide ]
$text = 'Extract the text with first 45 characters from this string.';
$nrw = 6;

echo join(" ", array_slice(str_word_count($text, 1, '0..9'), 0, $nrw));
 


Top
 Profile  
 
PostPosted: Tue Dec 10, 2013 1:47 am 
Offline
Forum Newbie

Joined: Mon Dec 09, 2013 11:52 am
Posts: 18
But if you have comma, dot or other punctuations in text, using array_slice() will lose the punctuations.


Top
 Profile  
 
PostPosted: Tue Dec 10, 2013 1:56 am 
Offline
Moderator
User avatar

Joined: Mon Nov 03, 2003 7:13 pm
Posts: 5975
Location: Odessa, Ukraine
It depends on what is actually needed. As the title goes, punctuation does not belong to 'words'


Top
 Profile  
 
PostPosted: Wed Dec 11, 2013 4:10 am 
Offline
Forum Newbie

Joined: Mon Dec 09, 2013 11:52 am
Posts: 18
Yes, You are right. I wrote that code to get the "n" first words from a text, that to add a Read more ..
In this usage is needed to keep the punctuations, and also not break words.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group