Created
October 20, 2011 10:32
-
-
Save 3en/1300851 to your computer and use it in GitHub Desktop.
Splits a PHP string by word count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** splitByWords | |
* | |
* Splits a string by $maxLength of words | |
* Based off the code: http://stackoverflow.com/questions/6604016/word-count-cut-off/6604052#6604052 | |
* | |
*/ | |
public static function splitByWords($text, $splitLength = 200) | |
{ | |
// explode the text into an array of words | |
$wordArray = explode(' ', $text); | |
// Too many words | |
if( sizeof($wordArray) > $splitLength ) | |
{ | |
// Split words into two arrays | |
$firstWordArray = array_slice($wordArray, 0, $splitLength); | |
$lastWordArray = array_slice($wordArray, $splitLength+1, sizeof($wordArray)); | |
// Turn array back into two split strings | |
$firstString = implode(' ', $firstWordArray); | |
$lastString = implode(' ', $lastWordArray); | |
return array($firstString, $lastString); | |
} | |
// if our array is under the limit, just send it straight back | |
return array($text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you are doing something wrong here or maybe I am applying it wrong. I have tested your code and it came out to be that while setting $lastWordArray at line number 18 you are using $splitLength+1.
But this will skip last word from first array.
As per my thinking it should be $splitLength only and not $splitLength+1.
0 - 10 means total 10 numbers including 0 (so basically 0,1,2,3,4,5,6,7,8,9)
I think you get you point.
Nice Idea. Happy Coding and Keep Contributing :)