Add space when a word is too long

php, string

Solution

If you're just looking to force your string to wrap rather than extending outside of its parent element, you can do that directly in css and not have to mess with your string at all:

p { 
  width: 100px; 
  word-wrap: break-word; 
}

<p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA</p>

That'll let the browser figure out where it needs to break rather than you trying to figure it out on the server.

Problem

My problem is the following. I have a string like this: ``` $string = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; ``` and I output this string in a container that's 100px wide. Is there any way I can automatically insert a space after 10 characters if any word is longer than 10 characters? ``` $string = chunk_split($string, 10); ``` is not a good solution because it inserts a space in the middle of a word. For example: ``` $string = "This is why chunk_split doesn't work"; $string = chunk_split($string, 10); echo $string; // OUTPUT: This is wh y chunk_sp lit doesn' t work ``` The point is that a space character allows the string to create a new line. Desired Output: ``` $string = "This is how it should work."; $string = function_i_am_looking_for($string); echo $string; // OUTPUT: This is how it should work. $string = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; $string = function_i_am_looking_for($string); echo $string; // OUTPUT: AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ```

Original source