开发者

PHP insert <br /> whenever substring is longer than x characters

I am trying to create some PHP code that will check the length of individual substrings within a string and insert "<开发者_JAVA技巧;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.


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.


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 />


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜