itools / smartstring
一个功能强大、以网页为中心的字符串操作库,具有自动HTML编码和流畅的PHP接口
Requires
- php: ^8.0
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^9.6
README
SmartString是一个PHP字符串处理库,让您能够更快、更轻松地编写更干净、更简单、更安全的代码。
而不是编写如下代码
echo "<h1>" . htmlspecialchars($article['title'], ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "</h1>"; $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, 200); // limit to 200 characters echo "Summary: " . htmlspecialchars($summary, ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5, 'UTF-8') . "...";
您可以编写如下代码
echo "<h1>$article->title</h1>"; echo "Summary: {$article->content->textOnly()->maxChars(120, '...')}\n";
SmartString自动处理HTML编码并提供常用任务的实用函数。这使得您的代码更简洁、更易读,并且本质上更安全。
目录
快速入门
通过Composer安装
composer require itools/smartstring
开始使用SmartString
require 'vendor/autoload.php'; use Itools\SmartString\SmartString; // Create SmartString ArrayObjects (can be referenced as array or object) $user = SmartString::fromArray(['name' => "John O'Reilly", 'id' => 123]); $request = SmartString::fromArray($_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();
功能和用法示例
创建SmartStrings
SmartString提供了简单的方法从各种数据类型创建对象。将$_REQUEST
或数据库记录数组转换为SmartString对象特别有用。
自动HTML编码功能意味着您无需多次调用htmlspecialchars()
,并且您还可以访问各种常见任务的实用方法。
// 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, use fromArray() to convert an existing array to an ArrayObject of SmartStrings $record = ['name' => "Jane Doe", 'age' => 25, 'isStudent' => true ]; $user = SmartString::fromArray($record); $request = SmartString::fromArray($_REQUEST); // or convert $_REQUEST to SmartString // Looping over a two-level array foreach (SmartString::fromArray($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']
流畅的链式接口
SmartString提供了一个流畅的、可链式接口,允许您在单行可读代码中执行一个或多个操作。
// 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, '...')}";
流畅的链式接口允许您逐步构建复杂的转换,使您的代码更直观、更易读、更易于维护。
自动HTML编码
SmartString通过默认自动HTML编码输出优先考虑网络安全性。这极大地简化了您的代码并有助于防止跨站脚本(XSS)漏洞。
每次您在字符串上下文中使用SmartString对象时,它都会自动HTML编码输出
$str = SmartString::new("It's easy!<hr>"); // SmartStrings return HTML-encoded output in string contexts echo $str; // "It's easy!<hr>" print $str; // "It's easy!<hr>" (string) $str; // "It's easy!<hr>" $new = $str."\n"; // "It's easy!<hr>\n"
访问值
您可以使用value()
方法访问原始值
$str = SmartString::new("It's easy!<hr>"); // Access the original value echo $str->value(); // "It's easy!<hr>"
或者您也可以使用noEncode()
别名方法以提高可读性。这在您有WYSIWYG内容且不想双重编码时很有用,并且您想明确表示该值未编码
echo <<<__HTML__ <h1>{$article->title}</h1> {$article->wysiwygContent->noEncode()} __HTML__;
使用ArrayObjects工作
当您将数组转换为SmartString时,您可以使用它像数组或对象一样使用。
$user = SmartString::fromArray(['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")}!";
类型转换
您可以使用终端方法将SmartString对象转换为不同类型。当您需要将SmartString值传递给期望特定类型的函数时,这可能很有用。
$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"
编码值
除了HTML编码之外,SmartString还提供了不同场景下显式编码的方法
$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"'
字符串操作
SmartString提供了多种常用字符串操作方法,使您轻松修改和格式化文本
// 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..."
数字格式化
SmartString提供了一种简单的方法来格式化数字,可以指定所需的十进制数和分隔符。您可以在脚本顶部或初始化文件中自定义默认格式,以便在整个应用程序中使用。
// 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"
您可以在PHP文档中找到可用的日期格式列表:[PHP日期格式](https://php.ac.cn/manual/en/datetime.format.php)
电话号码格式化
SmartString使用可自定义的规则格式化电话号码。您可以在脚本顶部或初始化文件中自定义默认格式,以便在整个应用程序中使用。
// 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"
数值运算
SmartString提供了一组用于执行基本算术和百分比计算的方法。这些方法可以链式调用,使得复杂的计算可以清晰简洁地表达。
// 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)
注意:在进行计算时要注意十进制精度问题。由于所有编程语言中固有的浮点数运算限制,结果有时可能会与预期值略有不同。
有关更多信息,请参阅[PHP浮点数](https://php.ac.cn/manual/en/language.types.float.php)。
条件运算
条件操作提供了在当前值为假、空白、null或零时提供备用值的简单方法。
// 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.
自定义函数
SmartString提供了一个apply()
方法,允许您使用自定义代码或PHP的内置函数。SmartString对象的值作为回调函数的第一个参数传递,之后是任何提供的参数。
apply()
方法的示例
$name = SmartString::new('John Doe'); // Using built-in PHP functions: $uppercase = $name->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) => "<b>$name</b>"); // returns "<b>John Doe</b>"
开发者调试与帮助
当您在SmartString对象上调用print_r()时,它将显示原始值
$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. )
调用SmartString::help()
或$obj->help()
将显示可用的方法和示例
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::fromArray(\$_REQUEST); // ArrayObject of SmartStrings Automatic HTML-encoding in string contexts: echo \$str; // "It's easy!<hr>" // ... continues with a list of available methods and examples
自定义默认设置
您可以通过在脚本顶部或初始化文件中添加以下内容来自定义默认值
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' => '# (###) ###-####'], ];
方法参考
除了下面的方法外,您还可以通过在脚本顶部或初始化文件中添加以下内容来自定义默认值
有疑问吗?
本库是为CMS Builder开发的,在此处的“CMS Builder”论坛发帖:[CMS Builder论坛](https://www.interactivetools.com/forum/)