Last active
September 2, 2015 20:55
-
-
Save wisecrab/cda33cb84b6368eb8c35 to your computer and use it in GitHub Desktop.
Split a string by word after $x amount of characters
This file contains hidden or 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
| <?php | |
| function splitStringByWords($x, $string) { | |
| //Convert the string | |
| $converted_string = explode( "\n", wordwrap( $string, $x)); | |
| //Return the array of split strings | |
| return $converted_string; | |
| } | |
| //Number of characters the split will occur after | |
| $x = 15; | |
| //Set the string variable that will be passed to the function | |
| $string = 'Here is my text string, you can use what ever string you would like here'; | |
| //Run the function | |
| $split_word_group = splitStringByWords($x, $string); | |
| //Access the data by using the array object | |
| echo $split_word_group[0] . '<br>'; | |
| /* Outputs the following: | |
| Here is my text | |
| */ | |
| //Loop the array | |
| for($i=0; $i < count($split_word_group); $i++) { | |
| echo $split_word_group[$i]; | |
| echo '<br>'; | |
| } | |
| /* Outputs the following: | |
| Here is my text | |
| string, you can | |
| use what ever | |
| string you | |
| would like here | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment