PHPackages                             itools/smartstring - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. itools/smartstring

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

itools/smartstring
==================

Enhanced PHP strings with automatic HTML encoding and chainable transformation methods

v2.6.2(2mo ago)1616↓50%2MITPHPPHP ^8.1

Since Aug 28Pushed 2mo agoCompare

[ Source](https://github.com/interactivetools-com/SmartString)[ Packagist](https://packagist.org/packages/itools/smartstring)[ Docs](https://github.com/interactivetools-com/SmartString)[ RSS](/packages/itools-smartstring/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (4)Versions (30)Used By (2)

SmartString: Secure and Simple String Handling for PHP
======================================================

[](#smartstring-secure-and-simple-string-handling-for-php)

SmartString is a PHP string handling library that lets you write cleaner, simpler, more secure code faster and with less effort.

Instead of writing code like this:

```
echo "" . htmlspecialchars($article['title'], ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "";
$summary = strip_tags($article['content']); // remove tags
$summary = html_entity_decode($summary, ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8'); // decode entities
$summary = substr($summary, 0, 120); // limit to 120 characters
echo "Summary: " . htmlspecialchars($summary, ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "...";
```

You can write code like this:

```
echo "$article->title";
echo "Summary: {$article->content->textOnly()->maxChars(120, '...')}\n";
```

SmartString handles HTML encoding automatically and provides utility functions for common tasks. This makes your code cleaner, more readable, and inherently more secure.

Table of Contents
-----------------

[](#table-of-contents)

- [SmartString: Secure and Simple String Handling for PHP](#smartstring-secure-and-simple-string-handling-for-php)
    - [Table of Contents](#table-of-contents)
    - [Quick Start](#quick-start)
    - [Features and Usage Examples](#features-and-usage-examples)
        - [Creating SmartStrings](#creating-smartstrings)
        - [Fluent Chainable Interface](#fluent-chainable-interface)
        - [Automatic HTML-encoding](#automatic-html-encoding)
        - [Accessing Values](#accessing-values)
        - [Working with SmartArrays](#working-with-smartarrays)
        - [Type Conversion](#type-conversion)
        - [Encoding Values](#encoding-values)
        - [String Manipulation](#string-manipulation)
        - [Number Formatting](#number-formatting)
        - [Date Formatting](#date-formatting)
        - [Phone Number Formatting](#phone-number-formatting)
        - [Numeric Operations](#numeric-operations)
        - [Conditional Operations](#conditional-operations)
        - [Validation](#validation)
        - [Error Checking](#error-checking)
        - [Developer-Friendly Error Messages](#developer-friendly-error-messages)
        - [Custom Functions](#custom-functions)
        - [Developer Debugging &amp; Help](#developer-debugging--help)
    - [Customizing Defaults](#customizing-defaults)
    - [Method Reference](#method-reference)
    - [Questions?](#questions)

Quick Start
-----------

[](#quick-start)

> **Requirements:** PHP 8.1 or higher with mbstring extension

Install via Composer:

```
composer require itools/smartstring
```

Start using SmartString:

```
require 'vendor/autoload.php';
use Itools\SmartString\SmartString;

// Create SmartArray of SmartStrings (can be referenced as array or object)
// Call ->asHtml() to convert all values to SmartStrings for HTML-safe output
$user    = SmartArray::new(['name' => "John O'Reilly", 'id' => 123])->asHtml();
$request = SmartArray::new($_REQUEST)->asHtml();

// Advanced: For direct instantiation with a specific type:
// $user = SmartArrayHtml::new(['name' => "John O'Reilly", 'id' => 123]);
// $data = SmartArrayRaw::new($rawData);  // For raw values without SmartStrings

// Use in string contexts for automatic HTML encoding
echo "Hello, $user->name!"; // Output: Hello, John O&apos;Reilly!

// Chain methods
echo $request->message->trim()->maxWords(50, '...');

// Access original values when needed
$userId = $user->id->value(); // Returns 123 as integer

// Check the actual value of a SmartString object (for debugging)
print_r($user->name);

// Access built-in help whenever you need it
SmartString::help();
$user->help();
```

Features and Usage Examples
---------------------------

[](#features-and-usage-examples)

### Creating SmartStrings

[](#creating-smartstrings)

SmartString offers simple ways to create objects from various data types. It can be especially useful to convert `$_REQUEST`, or database record arrays to SmartString objects.

The automatic HTML-encoding feature means you don't need to call `htmlspecialchars()`over and over again, and you get access to a variety of utility methods for common tasks.

```
// Single values
$name      = SmartString::new("John O'Reilly");
$age       = SmartString::new(30);
$price     = SmartString::new(19.99);
$isActive  = SmartString::new(true);
$nullValue = SmartString::new(null);

// Or use SmartArray::new()->asHtml() to convert an existing array to a SmartArray of SmartStrings
$record  = ['name' => "Jane Doe", 'age' => 25, 'isStudent' => true ];
$user    = SmartArray::new($record)->asHtml();
$request = SmartArray::new($_REQUEST)->asHtml();

// Looping over a two-level array
foreach (SmartArray::new($articles)->asHtml() as $article) {
    echo textOnly()->maxChars(200, '')}
        Read more
    __HTML__;
}

// Usage
echo $name;               // John O&apos;Reilly
echo $user->age;          // 25
echo $request->username;  // html-encoded $_REQUEST['username']
```

### Fluent Chainable Interface

[](#fluent-chainable-interface)

SmartString provides a fluent, chainable interface that allows you to perform one or more operations in a single, readable line of code.

```
// Providing a default value
echo "Hello, {$name->or('Guest')}!"; // e.g., "Hello, John!"

// Formatting a date
echo "Article date: {$article->date->dateFormat('M jS, Y')}"; // e.g., Jan 1st, 2024

// Formatting a number
echo "Total: {$order->total->numberFormat(2)}"; // e.g., 1,234.56

// Trimming whitespace
echo "";

// Combining multiple operations and providing a default value
echo "Order total: {$order->total->numberFormat(2)->or("none")}"; //

// Combining multiple operations
$url = "?startDate={$course->startDate->dateFormat('Y-m-d')->urlEncode()}";

// Combining multiple operations to create a text summary
echo "Summary: {$article->content->textOnly()->maxChars(200, '...')}";
```

The fluent chainable interface allows you to build complex transformations step-by-step, making your code more intuitive and easier to read and maintain.

### Automatic HTML-encoding

[](#automatic-html-encoding)

SmartString prioritizes web security by automatically HTML-encoding output by default. This greatly simplifies your code and helps prevent Cross-Site Scripting (XSS) vulnerabilities.

Whenever you use a SmartString object in a string context, it automatically HTML-encodes the output:

```
$str = SmartString::new("It's easy!");

// SmartStrings return HTML-encoded output in string contexts
echo $str;             // "It&apos;s easy!&lt;hr&gt;"
print $str;            // "It&apos;s easy!&lt;hr&gt;"
(string) $str;         // "It&apos;s easy!&lt;hr&gt;"
$new = $str."\n";      // "It&apos;s easy!&lt;hr&gt;\n"
```

### Accessing Values

[](#accessing-values)

You can access the original value with the `value()` method:

```
$str = SmartString::new("It's easy!");

// Access the original value
echo $str->value();    // "It's easy!"
```

Or you can also use the `rawHtml()` alias method for readability when outputting trusted HTML. This is useful when you have WYSIWYG content that you don't want to double-encode:

```
echo rawHtml()}
__HTML__;
```

### Working with SmartArrays

[](#working-with-smartarrays)

When you convert an array to SmartArray, you can use it like both an array and an object.

```
$user = SmartArray::new(['name' => 'John', 'age' => 30])->asHtml();

// Simple, clean object-style access (no extra curly braces needed)
echo "Name: $user->name, Age: $user->age";

// Array-style access still works too
echo "Hello, {$user['name']}!";

// For calling methods in strings, you still need to use curly braces
echo "Hello, {$user->name->or("User")}!";
```

### Type Conversion

[](#type-conversion)

You can convert SmartString objects to different types using terminal methods. This can be useful when you need to pass a SmartString value to a function that expects a specific type.

```
$value = SmartString::new("123.45");

// Convert to integer
echo $value->int(); // 123

// Convert to float
echo $value->float(); // 123.45

// Convert to boolean
echo $value->bool(); // true

// Convert to string
echo $value->string(); // "123.45"
```

### Encoding Values

[](#encoding-values)

Besides just HTML encoding, SmartString provides methods for explicit encoding in different scenarios:

```
$title = SmartString::new('apply('strtoupper');  // returns "JOHN DOE"

// Passing arguments to built-in functions:
$paddedValue = $name->apply('str_pad', 15, '.'); // returns "John Doe......."

// Writing your own custom function
$spacesToUnderscores = function($str) { return str_replace(' ', '_', $str); }; // anonymous function
$spacesToUnderscores = fn($str) => str_replace(' ', '_', $str);                 // arrow function (PHP 7.4+)
$urlSlug = $name->apply($spacesToUnderscores);   // returns "John_Doe"

// Applying inline arrow functions
$boldName = $name->apply(fn($val) => "$val"); // returns "John Doe"
```

### Developer Debugging &amp; Help

[](#developer-debugging--help)

When you call print\_r() on a SmartString object, it will display the original value with helpful information:

```
$name = SmartString::new("John O'Reilly");
print_r($name);

// Output:
Itools\SmartString\SmartString Object
(
    [README:private] => "Call $obj->help() for more information and method examples."
    [rawData:private] => "John O'Reilly"
)
```

This enhanced debugging output makes it easy to see the actual value stored in the object and provides guidance about how to get more detailed help.

Calling `SmartString::help()` or `$obj->help()` will display a list of available methods and examples:

```
This 'SmartString' object automatically HTML-encodes output in string contexts for XSS protection.
It also provides access to the original value, alternative encoding methods, and various utility methods.

Creating SmartStrings
\$str = SmartString::new("It's easy!");
\$req = SmartArray::new(\$_REQUEST)->asHtml();  // SmartArray of SmartStrings

Automatic HTML-encoding in string contexts:
echo \$str;             // "It&apos;s easy!&lt;hr&gt;"

// ... continues with a list of available methods and examples
```

Customizing Defaults
--------------------

[](#customizing-defaults)

You can customize the defaults by adding the following to the top of your script or in an init file:

```
SmartString::$numberFormatDecimal   = '.';             // Default decimal separator
SmartString::$numberFormatThousands = ',';             // Default thousands separator
SmartString::$dateFormat            = 'Y-m-d';         // Default dateFormat() format
SmartString::$dateTimeFormat        = 'Y-m-d H:i:s';   // Default dateTimeFormat() format
SmartString::$phoneFormat           = [                // Default phoneFormat() formats
    ['digits' => 10, 'format' => '(###) ###-####'],
    ['digits' => 11, 'format' => '# (###) ###-####'],
];
```

Method Reference
----------------

[](#method-reference)

In addition to the methods below, you can customize the defaults by adding the following to the top of your script or in an init file:

**Basic Usage**`SmartString::new($value)`Creates a new SmartString object from a single value`SmartArray::new($array)->asHtml()`Creates a new SmartArray from a regular PHP array with HTML-safe SmartString values`SmartArrayHtml::new($array)`Advanced: Direct instantiation of SmartArray with SmartString values`SmartArrayRaw::new($array)`Advanced: Direct instantiation of SmartArray with raw values`->value()`Returns the original, unencoded value**Type Conversion**`->int()`Returns the value as an integer`->float()`Returns the value as a float`->bool()`Returns the value as a boolean`->string()`Returns the value as a string (original value, not HTML-encoded)`SmartString::getRawValue()`Returns original value from Smart\* objects while leaving other types unchanged. Useful when working with mixed object/non-object values**Encoding Methods**`->htmlEncode()`Returns HTML-encoded string`->urlEncode()`Returns URL-encoded string`->jsonEncode()`Returns JSON-encoded string`->rawHtml()`Alias for `value()`, useful for readability when outputting trusted HTML content`->textToHtml()`Encodes special chars and converts newlines to ``, with option to preserve existing `` tags**String Manipulation**`->textOnly()`Removes HTML tags from the string, decodes entities, and trims whitespace`->trim()`Trims whitespace or specified characters from the string`maxWords($max, $ellipsis = '...')`Limits the string to a specific number of words`maxChars($max, $ellipsis = '...')`Limits the string to a specific number of characters**Formatting**`->dateFormat($format = default)`Formats the value as a date, using default or specified date format`->dateTimeFormat($format = default)`Formats the value as a date and time, using default or specified date format`->numberFormat($decimals = 0)`Formats the value as a number`->phoneFormat()`Formats the value as a phone number**Numeric Operations**`->percent($decimals = 0, $zeroFallback = null)`Converts value to percentage, with optional fallback for zero`->percentOf($total, $decimals = 0)`Calculates what percentage this number represents of $total`->add($value)`Adds $value to current number`->subtract($value)`Subtracts $value from current number`->multiply($value)`Multiplies current number by $value`->divide($divisor)`Divides current number by $divisor**Conditional Operations**`->or($fallback)`Returns the fallback if the value is missing ("", null), zero is not considered missing`->and($value)`Appends $value if the value is present (not "" or null), zero is considered present`->andPrefix($value)`Prepends $value if the value is present (not "" or null), zero is considered present`->ifNull($fallback)`Returns the fallback if the value is null`->ifBlank($fallback)`Returns the fallback if the value is an empty string`->ifZero($fallback)`Returns the fallback if the value is zero**Validation**`->isEmpty()`Returns true if the value is empty ("", null, false, 0, "0"), uses PHP empty()`->isNotEmpty()`Returns true if the value is NOT empty ("", null, false, 0, "0"), uses PHP !empty()`->isMissing()`Returns true if the value is missing (null or ""), zero is not considered missing`->isNull()`Returns true if the value is null**Error Checking**`->orDie($message)`Outputs message and exits if the value is missing ("", null), zero is not considered missing`->or404($message)`Outputs 404 header, message and exits if the value is missing ("", null), zero is not considered missing`->orThrow($message)`Throws Exception with message if the value is missing ("", null), zero is not considered missing`->orRedirect($url)`Redirects to URL if the value is missing ("", null), zero is not considered missing**Miscellaneous**`->apply($func, ...$args)`Applies a custom function to the value`->help()`Displays help information about available methods**See Also:** For array operations, check out our companion library `SmartArray`, a powerful companion library that provides array operations with chainable methods and seamless `SmartString`integration. SmartString and SmartArray are designed to work together as a pair for enhanced data handling:

Questions?
----------

[](#questions)

This library was developed for CMS Builder, post a message in our "CMS Builder" forum here:

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance86

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~20 days

Recently: every ~42 days

Total

28

Last Release

70d ago

Major Versions

v1.3.2 → v2.0.02024-11-27

PHP version history (2 changes)v1.0.0PHP ^8.0

v2.2.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/7710588a6f12bb1d6f8769445279c2ec60f1c5dc30c67fa9dc4931f361e20118?d=identicon)[itools](/maintainers/itools)

---

Top Contributors

[![daveedis](https://avatars.githubusercontent.com/u/22456364?v=4)](https://github.com/daveedis "daveedis (48 commits)")

---

Tags

jsonutf8stringsecuritymanipulationencodingmultibytehtmlformatfluentxssEscapesanitizestriptrimchainableUTFmethodstruncateurlencodesmartarray

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/itools-smartstring/health.svg)

```
[![Health](https://phpackages.com/badges/itools-smartstring/health.svg)](https://phpackages.com/packages/itools-smartstring)
```

###  Alternatives

[danielstjules/stringy

A string manipulation library with multibyte support

2.4k26.0M191](/packages/danielstjules-stringy)[voku/stringy

A string manipulation library with multibyte support

1783.8M19](/packages/voku-stringy)[xemlock/htmlpurifier-html5

HTML5 support for HTML Purifier

1052.9M11](/packages/xemlock-htmlpurifier-html5)[statamic/stringy

A string manipulation library with multibyte support, forked from @statamic

234.5M14](/packages/statamic-stringy)[tcb13/substringy

A sub string manipulation library with multibyte support that extends Stringy

1760.6k1](/packages/tcb13-substringy)[hallindavid/manny

a package of manipulators that hopefully come in useful for those of us who always forget regex when we need it (manny is short for manipulation)

38103.3k2](/packages/hallindavid-manny)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
