You could slice words that contain more than x characters using the following code.
It will first split the string into lines by using the function explode()
. It explodes on the <br />
tags. Then it will loop through the lines and split the line into words for each line. Then for each word it will add <br />
after every 5 characters. and add the edited line to the variable $new_string
. Ath the end it echoes variable $new_string
to display the edited string.
- To change the maximum word length, just change the variable
$max_length
.
- To change the input string, just change the variable
$string
.
Code
$string = 'aaa bbbbwer sdfr<br />ert tyuo sdh<br />ryt kkkkkkkkkkkk sdfg';
$max_length = 5;
$lines = explode('<br />', $string);
$new_string = '';
foreach($lines as $line)
{
$words = explode(' ', $line);
foreach($words as $word)
{
$new_string .= substr(chunk_split($word, $max_length, '<br />'), 0, -6) . ' ';
}
$new_string = substr($new_string, 0, -1) . '<br />';
}
echo $new_string;
Output
aaa bbbbw<br />er sdfr<br />ert tyuo sdh<br />ryt kkkkk<br />kkkkk<br />kk sdfg<br />