在字符串中的每个第12个字符后添加单词break标记

时间:2012-09-04 07:01:00

标签: php html string

$my_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."

预期结果:

"Lorem Ipsum <br/> is simply<br/> dummy text<br/>of the printing<br/> and typesetting<br/> industry."

标签应该在每第12个字符后添加,而不是像这样:

There are ma<br/>ny variations

6 个答案:

答案 0 :(得分:8)

尝试使用wordwrap。我认为它应该可以解决你的问题。

答案 1 :(得分:1)

试试这个

$newtext = wordwrap($text,12, "<br />");

答案 2 :(得分:0)

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
$newtext = wordwrap($text, 12, "<br />\n");

echo $newtext;

输出:

Lorem Ipsum
is simply
dummy text
of the
printing and
typesetting
industry. 


http://www.php.net/manual/en/function.wordwrap.php

答案 3 :(得分:0)

仅仅通过一个例子扩展Shakti的答案:

$my_string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
$my_wrapped_string = wordwrap($my_string, 12, '<br />');

$my_wrapped_string的值将为Lorem Ipsum<br />is simply<br />dummy text<br />of the<br />printing and<br />typesetting<br />industry.

答案 4 :(得分:0)

您的预期结果在空格和休息方面似乎非常不一致。听起来你想要一些自定义解决方案,就像你更喜欢的东西:

$array = $my_string.explode(" ");

counter = 0;
for(index=0; index<array.length; index++){
    counter += array[index].length+1;
    if(counter > 12){
        array[index-1] += "<br>"; //put some error handling here
        counter = 0;
    }
}

//then convert back to string and do whatever 
// - I tested this in JS and it worked fine

答案 5 :(得分:0)

<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);

echo "$newtext\n";
?>

以上示例将输出:

A very
long
woooooooooooooooooord.
and
something