Skip to content
PHP Logo

How can I make my PHP program insert a line break after exactly 40 characters when reading from a variable (e.g., database)?

To insert a line break after exactly 40 characters when reading from a variable in PHP, you can use the `wordwrap()` function. This function wraps a string to a given number of characters, breaking lines at word boundaries. By setting the second parameter to 40, you can ensure that a line break is inserted after every 40 characters.

php
// Read the content from the variable or database
$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

// Insert a line break after every 40 characters
$wrapped_content = wordwrap($content, 40, "\n", true);

// Output the wrapped content with line breaks
echo $wrapped_content;