greg0/string-builder

Simple PHP string builder inspired by C# StringBuilder

0.1 2018-09-20 19:10 UTC

This package is auto-updated.

Last update: 2024-11-21 20:59:06 UTC


README

Build Status Current Version PHP Version

Simple PHP string builder inspired by C# StringBuilder

Install

composer require greg0/string-builder

Sample usages

Creating string

$sb = new StringBuilder('Initial string');
$sb->append(' appended string');
$sb->appendLine();
$sb->appendLine('Other paragraph');
$sb->appendFormat('%s: %d', 'Value', 23);
$sb->appendLine();
$sb->append('End of poem.');

echo $sb->toString(); // echo (string)$sb;

Result:

Initial string appended string
Other paragraph
Value: 23
End of poem.

There are provided some string manipulation methods:

Insert string into position:

$sb = new StringBuilder('---[]---');
$sb->insert(4, 'o.o');

echo $sb->toString(); // ---[o.o]---
$sb = new StringBuilder('---[]---');
$sb->insert(4, 'o', 2);

echo $sb->toString(); // ---[oo]---

Removes the specified range of characters

$sb = new StringBuilder('Lorem ipsum dolor sit amet.');
$sb->remove(6, 5); // remove "ipsum"
echo $sb->toString(); // Lorem  dolor sit amet.

Replaces all occurrences of a specified string with another specified string

$sb = new StringBuilder('Lorem ipsum dolor sit amet.');
$sb->replace('ipsum', 'lirum');
echo $sb->toString(); // Lorem lirum dolor sit amet.

Clear string

$sb = new StringBuilder('Lorem ipsum dolor sit amet.');
$sb->clear();
echo $sb->toString(); // will return empty string

More examples provided in unit tests.

TODO

  • Encoding support
  • More test cases
  • Advanced "Format" method (see StringBuilder.AppendFormat)
  • Many different interface implementations (e.g. Streams)