moccalotto / stringy
简单、强大且流畅的字符串处理
0.4.1
2017-03-04 09:08 UTC
Requires
- php: >=7.0.0
- behat/transliterator: ^1.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.1
- phpspec/phpspec: ^3.0
This package is not auto-updated.
Last update: 2024-09-13 22:38:33 UTC
README
简单、强大且流畅的字符串处理
安装
要将此包添加为您的项目中的本地、项目级依赖项,只需在您的项目 composer.json
文件中添加对 moccalotto/stringy
的依赖。
这可以通过 composer 完成
composer require moccalotto/stringy
文档
Stringy
对象是不可变的。这意味着所有返回 新 Stringy
实例的操作 这意味着如果您需要对特定字符串执行两种不同的、分支的操作,则无需 clone
对象。
另一方面,您很可能无法通过身份比较两个 stringy 对象,因为它们通常非常短暂。在需要检查两个 stringy 对象是否包含相同字符串的情况下,我们建议使用 is()
方法。请参阅下面的示例
$s0 = str('Foo'); $s1 = $s0->lower(), $s2 = $s0->lower(); if ($s0 === $s1) { echo 'this code will not be executed'; } if ($s1 === $s2) { echo 'this code will not be executed'; } if ($s1->is($s2)) { echo 'this will work just fine'; } if (strval($s1) === strval($s2)) { echo 'this will also work'; }
构造函数
正常构造函数。
/** * Constructor. * * @param string $string the string contents of the Stringy object * @param string|null $currentEncoding the current encoding of $string */ public function __construct(string $string = '', string $currentEncoding = null)
静态工厂。
/** * Factory. * * @param Stringy|string $string The string to be Stringyfied. * If $string is a (descendant of) Stringy, it will * be cloned and converted to using $encoding * @param string|null $encoding The encoding of the $string * * @return Stringy */ public static function create($string = '', string $encoding = null)
辅助工厂函数。
/** * Stringify a string * * @param Stringy|string $string The string to be Stringyfied. * If $string is a (descendant of) Stringy, it will * be cloned and converted to using $encoding. * @param string|null $encoding The encoding of the $string * * @return Stringy */ function str($string = '', string $encoding = null) : Stringy
创建随机字符串。
/** * Factory for a random string of a given length. * * @return Stringy */ public static function random($length)
获取内容字符串。
/** * Get the content string of this object encoded as $encoding. * * @param string|null $encodedAs The encoding to get the string as. NULL = mb_internal_encoding * * @return string */ public function string($encodedAs = null) : string
字符串比较
/** * Compare this string to another. * * @param Stringy|string $string * * @return bool only true if the two strings are equal using strict (===) comparison. */ public function is($string) : bool
/** * Does the string contain $needle. * * @param Stringy|string $needle * @param int $index * * @return bool */ public function contains($needle, int $index = 0) : bool
/** * Does the string start with $needle ? * * @param Stringy|string $needle. * * @return bool */ public function startsWith($needle) : bool
/** * Does the string end with $needle ? * * @param Stringy|string $needle. * * @return bool */ public function endsWith($needle) : bool
长度(字符)
/** * Get the length (in characters) of the content string. * * @return int */ public function length() : int
大小(字节)
/** * Get the size (in bytes) of the content string. * * @return int */ public function size() : int
子字符串位置
/** * Find a the position of the first character of $needle within this string. * * @param Stringy|string $needle The string to search for * @param int $index Which occurrance of the string to get the position of. * 0 means the first match, 1 means the second match, etc. * -1 means the last match, -2 means the penultimate match, etc * * @return int|null The position of the first character of the $needle found. * NULL if $needle with the given $index could not be found * NOTE: that this behavior deviates from strpos in that strpos returns FALSE * in case $needle was not found. */ public function positionOf($needle, int $index = 0)
从字符串中获取单词和字符。
您可以通过 PHP 数组访问器语言构造来获取单个字符,如下所示
// Accessing individual characters: $str = str('foo bar baz'); $str[0]->string() === 'f'; // true $str[1]->string() === 'o'; // true $str[2]->string() === 'o'; // true $str[-3]->string() === 'b' // true $str[-2]->string() === 'a' // true $str[-1]->string() === 'z' // true $x = $str[30]; // OutOfRangeException
/** * Convert the content string into an array of words. * * Note that this method will not correctly split kanji, thai, braille, and * other scripts where words are not necessarily clearly bounded. * * @return Stringy[] */ public function words() : array
/** * Get an array of characters in the content string. * * @return Stringy[] */ public function characters() : array
映射/转换字符串
/** * Transform the string. * * @param callable $callable a function with the signature (Stringy $string) : Stringy|string * * @return Stringy */ public function transform(callable $callable)
示例
$str = str('foo bar baz'); $formatted = $str->transform(function (Stringy $stringy) { // the output of str_rot13() is a string // but it will automatically be converted to a // Stringy instance using the default character set. // If you return your own Stringy object, it will not be converted in any way. return str_rot13($stringy->asciiSafe()); }); print $formatted->string();
提取子字符串
/**
* Get a substring.
*
* @see https://php.ac.cn/manual/function.mb-substr.php
* for details about the $start and $length paramteers
*
* @param int $start The offset of the substring.
* If negative, it counts backwards
* from the end of the content string.
* @param int|null $length The length of the substring to extract.
* If negative, it counts backwards from
* the end of the content string.
* If NULL, the entire string after $start
* is extracted.
*
* @return Stringy
*/
public function substring(int $start, int $length = null)
基于搜索提取字符串的部分
提取给定搜索词之后的字符串部分。
/** * Get the part of the string that comes after $needle. * * @example: str('foo bar baz')->after('foo ') == 'bar baz' * * @param Stringy|string $needle * @param int $index Which occurrance of the string to search for: * 0 means the first match, 1 means the second match, etc. * -1 means the last match, -2 means the penultimate match, etc * * @return Stringy a clone of $this with a content string containing the * part that comes after $needle. If $needle is not * found, an empty Stringy is returned */ public function after($needle, int $index = 0)
提取给定搜索词之前的字符串部分。
/** * Get the part of the string before the first character of $needle. * * @example: str('foo bar baz')->before('foo ') == 'bar baz' * * @param Stringy|string $needle * @param int $index Which occurrance of the string to search for: * 0 means the first match, 1 means the second match, etc. * -1 means the last match, -2 means the penultimate match, etc * * @return Stringy a clone of $this with a content string containing the * part that comes after $needle. If $needle is not * found, an empty Stringy is returned */ public function before($needle, int $index = 0)
提取位于两个搜索词之间的字符串部分。
/** * Return the text that comes after $start and before $stop. * * @param Stringy|string $start * @param Stringy|string $stop * @param int $pairIndex search for the nth pair and * find what lies between those strings * * @return Stringy the string between $start and $stop */ public function between($start, $stop, int $pairIndex = 0)
基于搜索词删除字符串部分。
删除给定搜索词之后的字符串部分。
/** * Remove the substring that comes after the nth $needle. * * @param Stringy|string $needle * @param int $index * * @return Stringy */ public function removeAfter($needle, int $index = 0)
删除给定搜索词之前的字符串部分。
/** * Remove the substring that comes before the nth $needle. * * @param Stringy|string $needle * @param int $index * * @return Stringy */ public function removeBefore($needle, int $index = 0)
重复
重复字符串
/** * Repeat this string a number of times. * * @param int $times * * @return Stringy a string repeated $times times */ public function repeat(int $times)
/** * Remove repititions of substrings. * * If a substring is repeated 2 or more times in a row within the * content string,reduce it to being there only once. * * str('hello world')->unrepeat(' ') would be turned into 'hello world' * str('foo bar baz')->unrepeat(' ') would be turned into 'foo bar baz' * * @param Stringy|string $substring * * @return Stringy */ public function unrepeat($substring)
添加填充
/** * Append padding to the right hand side of the string. * * @param int $totalLengthOfResult the total length of the result string * @param Stringy|string $padding the padding character to use * * @return Stringy */ public function rightPadded(int $totalLengthOfResult, $padding = ' ')
/** * Prepend padding to the left hand side of the string. * * @param int $totalLengthOfResult the total length of the result string * @param Stringy|string $padding the padding character to use * * @return Stringy */ public function leftPadded(int $totalLengthOfResult, $padding = ' ')
/** * Add padding to both sides of the content string such that it becomes centered. * * @param int $totalLengthOfResult the total length of the result string * @param Stringy|string $padding the padding character to use * @param string $tieBreak Can either be "left" or "right". * In case the content string cannot be * centered, should the content string * be to the left of center or the right of * center. * * @return Stringy */ public function centered(int $totalLengthOfResult, $padding = ' ', $tieBreak = 'left')
删除填充
/** * Remove all instances of $needle from the beginning of the content string. * * @param Stringy|string $needle the substring to remove from the * beginning of the content string * * @return Stringy */ public function leftTrim($needle)
/** * Remove all instances of $needle from the end of the content string. * * @param Stringy|string $needle the substring to remove from the * end of the content string * * @return Stringy */ public function rightTrim($needle)
/** * Remove all occurances of $strings from the beginning of the content string. * * @param array $strings An array of strings or Stringy objects. * * @return Stringy */ public function leftTrimAll(array $strings)
/** * Remove all occurances of $strings from the end of the content string. * * @param array $strings An array of strings or Stringy objects. * * @return Stringy */ public function rightTrimAll(array $strings)
追加和前缀
/** * Append a string to $this. * * @param Stringy|string $other * * @return Stringy a clone of $this where contents of $other is prepended */ public function append($other)
/** * Prepend a string to $this. * * @param Stringy|string $other * * @return Stringy a clone of $this where contents of $other is prepended */ public function prepend($other)
/** * Surround the content string with two other strings. * * Essentially the same as calling prepend and append in one single operation. * * @param Stringy|string $left the string to be prepended to the content string * @param Stringy|string|null $right The string to be appended to the content string. * if NULL, the $left string will be used. * * @return Stringy */ public function surroundWith($left, $right = null)
调整大小写
/** * Convert the content string to uppercase. * * @return Stringy */ public function upper()
/** * Convert the content string to lowercase. * * @return Stringy */ public function lower()
/** * Turn the first letter of every word uppercase. * * Does not interfere with the casing of the rest of the letters. * Words are defined as strings separated by a word-boundary (such as white space, dashes, dots, etc.) * * @return Stringy */ public function ucwords()
/** * Turn the first letter of every word lowercase. * * Does not interfere with the casing of the rest of the letters. * Words are defined as strings separated by a word-boundary (such as white space, dashes, dots, etc.) * * @return Stringy */ public function lcwords()
/** * Turn first letter uppercased. * * Do not change the casing of the rest of the letters. */ public function ucfirst()
/** * Turn first letter lowercased. * * Do not change the casing of the rest of the letters. */ public function lcfirst()
拆分和合并
/** * Split the string into segments. * * @see https://php.ac.cn/manual/function.explode.php * * @param Stringy|string $pattern * @param int $limit * * @return Stringy[] array of strings as Stringy instances */ public function explode($pattern, int $limit = PHP_INT_MAX) : array
/** * Use the content string as glue to implode an array of strings. * * For instance: str(' + ')->glue(['this', 'that']) would yield the result "this + that". * * @see https://php.ac.cn/manual/function.implode.php * * @param array $strings An array of strings or Stringy objects that will be glued together. * * @return Stringy */ public function glue(array $strings)
替换和删除
/** * Replace all occurrences of the $search string with the $replacement string. * * @see https://php.ac.cn/manual/function.str-replace.php * * @param Stringy|string $search * @param Stringy|string $replace * * @return Stringy */ public function replace($search, $replace)
/** * Perform to => from translation. * * @see https://php.ac.cn/manual/function.strtr.php * * @param array $replacePairs an array in the form array('from' => 'to', ...). * * @return Stringy a Stringy where all the occurrences * of the array keys have been replaced by the corresponding values. * The longest keys will be tried first. * Once a substring has been replaced, * its new value will not be searched again. */ public function replaceMany(array $replacePairs)
/** * Remove a substring. (I.e. replace $search with an empty string). * * @param Stringy|string $search the substring to be removed * * @return Stringy */ public function remove($search)
** * Remove a number of substrings. * * @param array $searches an array of strings (or Stringy objects) * to be removed * * @return Stringy */ public function removeMany(array $searches)
转义
/** * Ensure that all characters are ASCII. * * Convert non-ascii characters to ASCII if possible (i.e. 'ü' is converted to 'u' and 'æ' to 'ae'). * Remove any characters that cannot be converted (i.e. most characters that are not based on the latin script). * * @return Stringy */ public function asciiSafe()
/** * Convert all non-ASCII characters into html entities. * * @see https://php.ac.cn/manual/function.htmlentities.php * * @param int $flags See php documentation for htmlentities * * @return Stringy */ public function entityEncoded(int $flags = ENT_QUOTES | ENT_HTML5)
/** * Escape this string for use as html text. * * @see https://php.ac.cn/manual/function.htmlspecialchars.php * * @param int $flags See php documentation for htmlspecialchars * * @return Stringy */ public function escapeForHtml(int $flags = ENT_QUOTES | ENT_HTML5)
/** * Escape a string so it can be used in a regular expression. * * @param Stringy|string $delimiter the delimiter used to start and * terminate the regular expression. * Usually the forward slash will be * used to encluse regular expression. * * @return Stringy|string */ public function escapeForRegex($delimiter)
格式化
/** * Include the content string in another, using sprintf syntax. * * @see https://php.ac.cn/manual/function.sprintf.php * * @param Stringy|string $string The sprintf-template string to use. * Must include at least one "%s" * @param array $extraParams extra params to use in the sprintf operation * * @return Stringy */ public function includeIn($string, array $extraParams = []) // example: str('bar')->includeIn('foo %s baz')->is('foo bar baz'); // true str('bar')->includeIn('foo %s %s', ['baz'])->is('foo bar baz'); // true
/** * Use the content string as a sprintf-template string. * * @see https://php.ac.cn/manual/function.vsprintf.php * * @param array $args an array of args to use á la vsprintf * * @return Stringy */ public function format(array $args)