php - Auto spacebar after a word with over 50 characters

92

Is there a function that can automatically add a spacerbar if a word is over a certain number of characters? For example, given a word with 100 characters, it will post a spacebar at the 50th character. I am creating a comment system, and if someone posts something like:

ASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDF

it will mess up the look of my layout because there is no space in the word.

362

Answer

Solution:

Use CSS instead of changing the actual word/string:

div{
    display:table;
    word-break:break-all;
}

Demo

831

Answer

Solution:

To answer with PHP, you can use a function like this one (if you really need to):

<?php
$str = '1234567890123456789012345678901234567890123456789 123456789012345678901234567890123456789012345678901234567890 ASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDFASDF';

function addSpace($str,$int){
 $output = '';
 $words = explode(' ', $str);
 foreach ($words as $word):
     $new = '';
     while(strlen($word)>$int){
     $new .= substr($word, 0, $int). ' ';
     $word = substr($word, $int);
     }
     $output .= "$new $word ";
 endforeach;
 return $output;
}
echo addSpace($str, 50);
?>

People are also looking for solutions to the problem: php - Encrypt configuration from everybody including developer

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.