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)
// Call ->withSmartStrings() to convert all values to SmartStrings, or use SmartArray::new($array, true)
$user = SmartArray::new(['name' => "John O'Reilly", 'id' => 123])->withSmartStrings(); // verbose syntax
$user = SmartArray::new(['name' => "John O'Reilly", 'id' => 123], true); // shortcut syntax
$request = SmartArray::new($_REQUEST, true);
// 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);
// Or use SmartArray::new()->withSmartStrings() to convert an existing array to a SmartArray of SmartStrings
$record = ['name' => "Jane Doe", 'age' => 25, 'isStudent' => true ];
$user = SmartArray::new($record)->withSmartStrings();
$request = SmartArray::new($_REQUEST, true); // shortcut syntax, pass true as second arg, new($array, true)
// Looping over a two-level array
foreach (SmartArray::new($articles, true) 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])->withSmartStrings(); // shortcut syntax new($array, true)
// 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"
// raw HTML - This is an alias for value() for readability when outputting trusted HTML
echo "Title: {$title->rawHtml()}"; // '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 with 2 decimals, and fallback value for 0
$value = SmartString::new(0);
echo $value->percent(2, "N/A"); // "N/A"
// Percentage of a total
$score = SmartString::new(24);
echo $score->percentOf(100); // "24%"
// Addition
$base = SmartString::new(100);
echo $base->add(50); // 150
// Handling null values (treated as zero by default)
$value = SmartString::new(null);
echo $value->add(50); // 50
// 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
// Chaining operations
$price = SmartString::new(100);
echo $price->multiply(1.1)->divide(2)->percent(); // "55%" (add tax, divide by 2, show as percent)
// Math operations can be useful for simple reporting, calculating totals, discounts, taxes, etc.
Order Total: $order->total->add( $order->shipping )->numberFormat(2)
// or($newValue): Show default if value is missing ("", null). Zero is not considered missing.
$value = SmartString::new('');
echo $value->or('Default'); // "Default"
// and($value): Append a value if the value is present (not "" or null). Zero is considered present.
echo $record->address1->and(",<br>\n");
echo $record->address2->and(",<br>\n");
echo $record->address3->and(",<br>\n");
// andPrefix($value): Prepend a value if the value is present (not "" or null). Zero is considered present.
echo $record->phone->andPrefix("Phone: ");
// 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->int()} 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.
$value = SmartString::new('');
if ($value->isEmpty()) {
echo "Value is empty!";
}
$value = SmartString::new('Hello');
if ($value->isNotEmpty()) {
echo "Value is not empty!";
}
$value = SmartString::new(null);
if ($value->isNull()) {
echo "Value is specifically NULL!";
}
$value = SmartString::new('');
if ($value->isMissing()) {
echo "Value is missing (null or empty string)!";
}
// Terminate with 404 if record not found
$article = DB::get('articles', 123); // Assume SmartArray returned
$article->id->or404("Article not found"); // Sends 404 header and terminate script
// Terminate with custom message if value missing
$article = DB::get('articles', 123); // Assume SmartArray returned
$article->id->orDie("Article not found"); // Output message and terminate script
$article->id->orThrow("Article not found"); // Throws Exception with error message
// Common error: Forgetting to use parentheses on methods
$name = SmartString::new("John");
echo $name->trim; // Will show helpful error: "Method ->trim needs brackets() everywhere and {curly braces} in strings"
// Common error: Forgetting curly braces in strings
echo "Hello $name->trim()"; // Will show helpful error explaining you need to use: "Hello {$name->trim()}"
$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 '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 = SmartArray::new(\$_REQUEST)->withSmartStrings(); // SmartArray of SmartStrings
Automatic HTML-encoding in string contexts:
echo \$str; // "It's easy!<hr>"
// ... continues with a list of available methods and examples