Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space when a word is too long

Tags:

string

php

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
like image 704
Jonas Kaufmann Avatar asked Dec 12 '22 17:12

Jonas Kaufmann


2 Answers

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.

like image 146
ultranaut Avatar answered Dec 24 '22 06:12

ultranaut


Use wordwrap() Wordwrap cuts the sentence by full words before to reach the max width. In the next example I turned true the last parameter to force the cut always with 10 characters.

$short = wordwrap($string, 10, PHP_EOL, true);

another option is

$short = wordwrap($string, 10, '<br>', true);

However cut by number of characters is not safe since not always the width of the chars is the same (different font types)

The best option is place a <div> over the last part of the sentence.

like image 37
Maks3w Avatar answered Dec 24 '22 07:12

Maks3w