Download the PHP package itools/smartstring without Composer
On this page you can find all versions of the php package itools/smartstring. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download itools/smartstring
More information about itools/smartstring
Files in itools/smartstring
Package smartstring
Short Description Enhanced strings with automatic HTML encoding and chainable methods
License MIT
Homepage https://github.com/interactivetools-com/SmartString
Informations about the package smartstring
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:
You can write code like this:
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
- SmartString: Secure and Simple String Handling for PHP
- Table of Contents
- Quick Start
- Features and Usage Examples
- Creating SmartStrings
- Fluent Chainable Interface
- Automatic HTML-encoding
- Accessing Values
- Working with SmartArrays
- Type Conversion
- Encoding Values
- String Manipulation
- Number Formatting
- Date Formatting
- Phone Number Formatting
- Numeric Operations
- Conditional Operations
- Validation
- Error Checking
- Developer-Friendly Error Messages
- Custom Functions
- Developer Debugging & Help
- Customizing Defaults
- Method Reference
- Questions?
Quick Start
Requirements: PHP 8.0 or higher with mbstring extension
Install via Composer:
Start using SmartString:
Features and Usage Examples
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.
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.
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
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:
Accessing Values
You can access the original value with the value()
method:
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:
Working with SmartArrays
When you convert an array to SmartArray, you can use it like both an array and an object.
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.
Encoding Values
Besides just HTML encoding, SmartString provides methods for explicit encoding in different scenarios:
String Manipulation
SmartString offers a variety of methods for common string operations, making it easy to modify and format your text:
And all of the above methods are chainable:
Number Formatting
SmartString provides a simple way to format numbers specifying the number of decimals and separators as needed. You can customize the default formats at the top of your script or in an init file to use throughout your application.
Date Formatting
You can format dates with a standard format for date, datetime, or specify a custom format as needed. You can customize the default formats at the top of your script or in an init file to use throughout your application.
You can find a list of available date formats in the PHP documentation: https://www.php.net/manual/en/datetime.format.php
Phone Number Formatting
SmartString formats phone numbers using customizable rules. You can customize the default formats at the top of your script or in an init file to use throughout your application.
Numeric Operations
SmartString provides a set of methods for performing basic arithmetic and percentage calculations. These methods are chainable, allowing for complex calculations to be expressed clearly and concisely. Null values are treated as zero by default, making calculations more intuitive.
Note: Be aware of decimal precision issues when performing calculations. Results may sometimes differ slightly from expected values due to floating-point arithmetic limitations inherent in all programming languages.
For more information, see PHP Floating Point Numbers.
Conditional Operations
Conditional operations provide a simple way to provide a fallback value when the value is missing ("", null) or handle specific conditions like null or zero values.
Validation
Check if a value meets specific conditions using validation methods:
Error Checking
Show an error message, throw an exception, or display a 404 page for values that are missing (empty string "", null). Zero is not considered missing.
Developer-Friendly Error Messages
SmartString provides detailed error messages when methods are used incorrectly. This makes debugging easier, especially when working with strings:
Custom Functions
SmartString provides an apply()
method that allows you to use custom code or PHP's built-in functions.
The value of the SmartString object is passed as the first argument to the callback function
followed by any supplied arguments.
Examples of using apply():
Developer Debugging & Help
When you call print_r() on a SmartString object, it will display the original value with helpful information:
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:
Customizing Defaults
You can customize the defaults by adding the following to the top of your script or in an init file:
The $treatNullAsZero
setting controls how null values are handled in numeric operations:
- When
true
(default): null values are treated as 0, making calculations more intuitive - When
false
: operations with null values return null results, useful for detecting uninitialized values or using -> or()
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)->withSmartStrings() |
Creates a new SmartArray from a regular PHP array. All nested arrays and values are converted to SmartArray and SmartString objects |
SmartArray::new($array, true) |
Shortcut syntax to create a new SmartArray with SmartStrings from a regular PHP array |
->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 |
String Manipulation | |
->textOnly() |
Removes HTML tags from the string, decodes entities, and trims whitespace |
->nl2br() |
Converts newlines to HTML line breaks |
->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) |
Converts value to percentage |
->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 |
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:
https://github.com/interactivetools-com/SmartArray?tab=readme-ov-file#method-reference
Questions?
This library was developed for CMS Builder, post a message in our "CMS Builder" forum here: https://www.interactivetools.com/forum/
All versions of smartstring with dependencies
ext-mbstring Version *