1. Go to this page and download the library: Download itools/smartstring library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Itools\SmartString\SmartString;
// Create SmartArray of SmartStrings (can be referenced as array or object)
$user = SmartArray::new(['name' => "John O'Reilly", 'id' => 123]);
$request = SmartArray::new($_REQUEST);
// Use in string contexts for automatic HTML encoding
echo "Hello, $user->name!"; // Output: Hello, John O'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();
// 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);
// Easier way, SmartString::new() to convert an existing array to a SmartArray of SmartStrings
$record = ['name' => "Jane Doe", 'age' => 25, 'isStudent' => true ];
$user = SmartString::new($record);
$request = SmartString::new($_REQUEST); // or convert $_REQUEST to SmartString
// Looping over a two-level array
foreach (SmartString::new($articles) as $article) {
echo <<<__HTML__
<h1>$article->title</h1>
<p>{$article->content->textOnly()->maxChars(200, '')}</p>
<a href="read.php?id={$article->id->urlEncode()}">Read more</a>
__HTML__;
}
// Usage
echo $name; // John O'Reilly
echo $user->age; // 25
echo $request->username; // html-encoded $_REQUEST['username']
// 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 "<input type='text' name='username' value='{$user->name->trim()}'>";
// 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, '...')}";
$user = SmartArray::new(['name' => 'John', 'age' => 30]);
// 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")}!";
$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"
$title = SmartString::new('<10% OFF "SALE"');
// Original Value
echo $title->value(); // '<10% OFF "SALE"'
// HTML Encode (default) - can be called explicitly for readability
echo $title->htmlEncode(); // "<10% OFF "SALE""
// URL encode
echo "add.php?title={$title->urlEncode()}"; // add.php?title=%3C10%25+OFF+%22SALE%22
// JSON encode
echo "let title={$title->jsonEncode()}"; // let title="\u003C10% OFF \u0022SALE\u0022"
// No encode - This is an alias for value() for readability in string contexts
echo "Title: {$title->noEncode()}"; // 'Title: <10% OFF "SALE"'
// Convert HTML to text - removes tags, decodes entities, and trims whitespace
$htmlText = SmartString::new(" <b> Some HTML </b> ");
echo $htmlText->textOnly(); // "Some HTML"
// Convert newlines to <br> tags - useful for displaying multi-line text in HTML
$multiLineText = SmartString::new("Hello\nWorld");
echo $multiLineText->nl2br(); // "Hello<br>\nWorld"
// Trim whitespace
$whitespaceText = SmartString::new(" Trim me ");
echo $whitespaceText->trim(); // "Trim me"
// Limit to a specific number of words
$longText = SmartString::new("The quick brown fox jumps over the lazy dog");
echo $longText->maxWords(4); // "The quick brown fox..."
// Limit to a specific number of characters, up to the last whole word
echo $longText->maxChars(10); // "The quick..."
// Be sure to convert HTML to text before using maxChars or maxWords
echo $htmlText->textOnly()->maxChars(10); // "Some HTML"
$str = SmartString::new(" <p>More text and HTML than needed</p> ");
echo $str->textOnly()->maxWords(3); // "More text and..."
// Basic number formatting with default arguments
$number = SmartString::new(1234567.89);
echo $number->numberFormat(); // "1,234,567"
// Formatting options can be customized to match your locale or regional preferences
SmartString::$numberFormatDecimal = ','; // Decimal separator, default is '.'
SmartString::$numberFormatThousands = ' '; // Thousands separator, default is ','
// Specify number of decimals
echo $number->numberFormat(2); // "1 234 567,89"
// Set default date and date-time formats
SmartString::$dateFormat = 'F jS, Y'; // Example: September 10th, 2024
SmartString::$dateTimeFormat = 'F jS, Y g:i A'; // Example: September 10th, 2024 3:45 PM
// Using default date-only format
$date = SmartString::new("2024-05-15 14:30:00");
echo $date->dateFormat(); // "May 15th, 2024"
// Using default date-time format
$dateTime = SmartString::new("2024-06-21 17:30:59");
echo $dateTime->dateTimeFormat(); // "June 21st, 2024 5:30 PM"
// Custom format
echo $date->dateFormat('F j, Y'); // "May 15, 2024"
echo $dateTime->dateTimeFormat('l, F j, Y g:i A'); // "Friday, June 21, 2024 5:30 PM"
// Handling invalid dates - returns null
$invalid = SmartString::new("not a date");
echo $invalid->dateFormat()->or("Invalid date"); // "Invalid date"
echo $invalid->dateFormat()->or($invalid); // "not a date"
// Specify preferred phone formats
SmartString::$phoneFormat = [
['digits' => 10, 'format' => '1.###.###.####'], // Automatically adds country code
['digits' => 11, 'format' => '#.###.###.####'],
];
// 10-digit phone number - only numbers are kept when formatting
$phone = SmartString::new("(234)567-8901");
echo $phone->phoneFormat(); // "1.234.567.8901"
// 11-digit phone number
$phone = SmartString::new("1-888-123-4567");
echo $phone->phoneFormat(); // "1.888.123.4567"
// Invalid phone number - returns null
$phone = SmartString::new("123");
echo $phone->phoneFormat()->or("Invalid phone"); // default message if null
echo $phone->phoneFormat()->or($phone); // or show the original value "123"
// Percentage conversion
$ratio = SmartString::new(0.75);
echo $ratio->percent(); // "75%"
// Percentage of a total
$score = SmartString::new(24);
echo $score->percentOf(100); // "24%"
// Addition
$base = SmartString::new(100);
echo $base->add(50); // 150
// Subtraction
$start = SmartString::new(100);
echo $start->subtract(30); // 70
// Division
$total = SmartString::new(100);
echo $total->divide(4); // 25
// Multiplication
$factor = SmartString::new(25);
echo $factor->multiply(4); // 100
// Math operations can be useful for simple reporting, calculating totals, discounts, taxes, etc.
Order Total: $order->total->add( $order->shipping )->numberFormat(2)
// or($newValue): Handling falsy values (false, null, zero, or empty string)
$value = SmartString::new('');
echo $value->or('Default'); // "Default"
// ifBlank($newValue): Handling blank values (only on empty string "")
$name1 = SmartString::new('');
$name2 = SmartString::new('Alice');
echo $name1->ifBlank('John Doe'); // "John Doe"
echo $name2->ifBlank('John Doe'); // "Alice"
// ifNull($newValue): Handling null values - SmartString will return nulls on failed operations
$nullable = SmartString::new(null);
echo $nullable->ifNull('Not Null'); // "Not Null"
// ifZero($newValue): Handling zero values (0, 0.0, "0", or "0.0")
$zero = SmartString::new(0);
echo $zero->ifZero('No balance'); // "No balance"
// if($condition, $valueIfTrue): Change value if condition is true
$eggs = SmartString::new(12);
echo $eggs->if($eggs->int() === 12, "Full Carton"); // "Full Carton"
// set($newValue): Assign a new value or expression result to the current object
$price = SmartString::new(19.99);
echo $price->set('24.99'); // 24.99
echo $price->set($price->value() < 20 ? "Under 20" : "Over 20"); // "Over 20"
// Or more complex operations using PHP match() expressions
$eggs = SmartString::new(12);
echo <<<__HTML__
Eggs: {$eggs->set(match($eggs->int()) {
12 => "Full Carton",
6 => "Half Carton",
default => "$eggs Eggs"
})}
__HTML__; // "Eggs: Full Carton"
// The above code is pretty complex, so it's best to use it sparingly. Don't be afraid to
// use regular PHP code when needed. We always recommend using the best tool for the job.
$name = SmartString::new("John O'Reilly");
print_r($name);
// Output:
Itools\SmartString\SmartString Object
(
[value] => "John O'Reilly"
[docs] => Developers, call $obj->help() for more information and method 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!<hr>");
\$req = SmartString::new(\$_REQUEST); // SmartArray of SmartStrings
Automatic HTML-encoding in string contexts:
echo \$str; // "It's easy!<hr>"
// ... continues with a list of available methods and examples