2

I am trying to create some PHP code that will check the length of individual substrings within a string and insert "<br />" whenever a substring is longer than x characters.

The string is always of the following form:
aaa bbbbwer sdfr<br />ert tyuo sdh<br />ryt kkkkkkkkkkkk sdfg

So, say x=5, then I want that string to be converted into:
aaa bbbbw<br />er sdfr<br />ert tyuo sdh<br />ryt kkkkk<br />kkkkk<br />kk sdfg

How do I do this? Pls help!

Thanks a lot.

RLJ
  • 135
  • 2
  • 6
  • 10

3 Answers3

5

i think you can try wordwrap

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

Result

The quick brown fox<br />
jumped over the lazy<br />
dog.
Harish
  • 2,311
  • 4
  • 23
  • 28
  • This does not split the words on every 5 characters like the OP asked for. – Michiel Pater Mar 21 '11 at 14:03
  • 1
    @Michiel Pater: yeah i just suggested an easier way to handle , i thought he might have designed the string unknowing of this function ! your answer is to the point , i just gave a suggetion – Harish Mar 21 '11 at 14:05
2

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 />
Michiel Pater
  • 22,377
  • 5
  • 43
  • 57
0

And the wordwrap function don't make whats you wants ?

Yoann
  • 4,937
  • 1
  • 29
  • 47
  • This does not split the words on every 5 characters like the OP asked for. – Michiel Pater Mar 21 '11 at 14:05
  • Thanks for the quick replies! Although Michiel's answer probably addresses best the problem as I wrote it here, using wordwrap will work fine as well. Cheers! – RLJ Mar 21 '11 at 15:22
  • @RLJ I've merged your accounts together, you can now accept an answer as correct. I'd suggest you register; also, [please read this Faq entry about cookie-based accounts.](http://meta.stackexchange.com/questions/44557/why-should-i-register-my-account/44562#44562) –  Mar 21 '11 at 15:43