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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With