zoliszabo / php-mlstring
A pretty simple multiline strings library
Installs: 2
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/zoliszabo/php-mlstring
Requires
- php: >=7.3
Requires (Dev)
- phpunit/phpunit: ^9.6
README
A pretty simple multi-line strings library.
โ Are you tired of using:
- long (loooooooong) strings with
\nand\r\n? - concatenation to make your strings readable?
- heredoc syntax with its crazy indentation rules?
๐ This library allows you to use multi-line strings in a more readable way.
๐ Instead of this:
$longString = "This is a long string\n" . "that spans multiple lines\n" . "and uses concatenation to be readable.";
๐ or this:
$longString = <<<EOD This is a long string that spans multiple lines and uses heredoc syntax to be readable. EOD;
๐ You can use this:
$longString = MLString( "This is a long string", "that spans multiple lines", "and uses MLString to be readable." );
Installation
You can install this library using Composer. Run the following command in your terminal:
composer require zoliszabo/mlstring
Usage
-
The class constructor accepts any number of string arguments, which will be concatenated together with a newline character (
PHP_EOL) between them:use MLString\MLString; $mlString = new MLString( "This is a long string", "that spans multiple lines", "and uses MLString to be readable." ); echo $mlString; // Outputs the multi-line string
-
Alternatively, you can use the
MLString::of()static method to create an instance ofMLString:use MLString\MLString; $mlString = MLString::of( "This is a long string", "that spans multiple lines", "and uses MLString to be readable." ); echo $mlString; // Outputs the multi-line string
-
Finally, you can also use the
MLStringfunction as a shortcut:use function MLString\MLString; $mlString = MLString( "This is a long string", "that spans multiple lines", "and uses MLString to be readable." ); echo $mlString; // Outputs the multi-line string
Real-world usage example
use function MLString\MLString; throw new \Exception( MLString( "This is a multi-line exception message.", "It can span multiple lines for better readability.", "You can use it just like a regular string." ) );
Custom glue strings
Starting version 2, you can customize the string that is used to join the lines together by calling the withGlue(...), withNewLine() or withSpace() methods on the MLString instance:
use MLString\MLString; $mlString = MLString::of( "This is a long string", "that spans multiple lines", "and uses MLString to be readable.", ); echo $mlString->withGlue(' | '); // Outputs: "This is a long string | that spans multiple lines | and uses MLString to be readable." echp $mlString->withSpace(); // Outputs: "This is a long string that spans multiple lines and uses MLString to be readable." echo $mlString->withNewLine(); // Outputs the original string with new lines