Skip to content

Instantly share code, notes, and snippets.

@bambinoua
Created October 14, 2022 15:45
Show Gist options
  • Save bambinoua/4ba612aea61808c61109d43cbce0d8dd to your computer and use it in GitHub Desktop.
Save bambinoua/4ba612aea61808c61109d43cbce0d8dd to your computer and use it in GitHub Desktop.
Split long text onto few lines of specified length
<?php
$count = 60;
$re = "/(?:((?>.{1,${count}}(?:(?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|.{1,${count}})(?:\r?\n)?|(?:\r?\n|$))/";
$string = 'This function will always return an array even the if the text is not processed i.e. for already short text. The above code returns the unprocessed short text by adding it into array.';
echo trim(preg_replace($re, "$1\r\n", $string));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment