[关闭]
@fzbing 2015-08-06T02:20:37.000000Z 字数 19815 阅读 682

danielstjules Stringy

document


Stringy

一个支持多字节的PHP字符串操作库。兼容 PHP 5.3+ 和 HHVM。参考 1.x 分支的文档。

  1. s('string')->toTitleCase()->ensureRight('y') == 'Stringy'

Build Status

Why? 为什么要用?

In part due to a lack of multibyte support (including UTF-8) across many of
PHP's standard string functions. But also to offer an OO wrapper around the
mbstring module's multibyte-compatible functions. Stringy handles some quirks,
provides additional functionality, and hopefully makes strings a little easier
to work with!

  1. // Standard library
  2. strtoupper('fòôbàř'); // 'FòôBàř'
  3. strlen('fòôbàř'); // 10
  4. // mbstring
  5. mb_strtoupper('fòôbàř'); // 'FÒÔBÀŘ'
  6. mb_strlen('fòôbàř'); // '6'
  7. // Stringy
  8. s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'
  9. s('fòôbàř')->length(); // '6'

Installation 安装

如果你在用 Composer 管理依赖,把下面实例加入你的 composer.json 文件:

  1. "require": {
  2. "danielstjules/stringy": "~2.0"
  3. }

然后,在运行 composer update or php composer.phar update 后。你就可以利用 Composer 的自动加载了:

  1. require 'vendor/autoload.php';

另外,你也可以简单的直接引入文件:

  1. require_once 'path/to/Stringy/src/Stringy.php';

我建议你在任何情况下,都用别名:

  1. use Stringy\Stringy as S;

Please note that Stringy relies on the mbstring PHP module for its underlying
multibyte support. This is a non-default, but very common module. For example,
with debian and ubuntu, it's included in libapache2-mod-php5, php5-cli, and
php5-fpm. For OSX users, it's a default for any version of PHP installed with
homebrew. If compiling PHP from scratch, it can be included with the
--enable-mbstring flag.

OO and Chaining

该库提供了面向对象的链式调用,如下:

  1. use Stringy\Stringy as S;
  2. echo S::create('fòô bàř')->collapseWhitespace()->swapCase(); // 'FÒÔ BÀŘ'

当把对象用在字符串上下文中时,它会返回当前字符串,例:

  1. (string) S::create('foo') // 'foo'

Implemented Interfaces 实现的接口

Stringy\Stringy 实现了 IteratorAggregate 接口, 意味着Stringy的实例可以用于 foreach

  1. $stringy = S::create('fòôbàř');
  2. foreach ($stringy as $char) {
  3. echo $char;
  4. }
  5. // 'fòôbàř'

它实现了 Countable 接口,使 count() 可用:

  1. $stringy = S::create('fòô');
  2. count($stringy); // 3

此外,实现了 ArrayAccess 接口。使 isset() 可用于检查特定索引是否有字符。
因为 Stringy\Stringy 是不可变的,任何 offsetSet or offsetUnset 调用将抛出异常。
offsetGet 可用,并且接收正负索引。无效的索引会抛出 OutOfBoundsException

  1. $stringy = S::create('bàř');
  2. echo $stringy[2]; // 'ř'
  3. echo $stringy[-2]; // 'à'
  4. isset($stringy[-4]); // false
  5. $stringy[3]; // OutOfBoundsException
  6. $stringy[2] = 'a'; // Exception

PHP 5.6 Creation 为 PHP 5.6 创作。

自 PHP 5.6 起,use function 可以用来导入函数。
Stringy 暴露了一个命名空间化的函数,Stringy\create,它与 Stringy\Stringy::create() 功能一样。
如果你正在用 PHP 5.6 或者别的支持 use function 语法的运行环境,你可以利用更简单的 API:

  1. use function Stringy\create as s;
  2. // Instead of: S::create('fòô bàř')
  3. s('fòô bàř')->collapseWhitespace()->swapCase();

Class methods 类方法

create(mixed $str [, $encoding ]) 创建对象

创建一个 Stringy 对象并且指定 str 和编码。
$str 期待 string 类型。如果 $encoding 没有指定,它将默认为 mb_internal_encoding() 返回值。
该方法返回 实例化的对象。如果第一个参数是没有 __toString 方法的 array 或者 object 将抛出 InvalidArgumentException

  1. $stringy = S::create('fòôbàř', 'UTF-8'); // 'fòôbàř'

Instance Methods 实例方法

Stringy objects are immutable.
All examples below make use of PHP 5.6 function importing, and PHP 5.4 short array syntax.
They also assume the encoding returned by mb_internal_encoding() is UTF-8.
For further details, see the documentation for the create method above, as well as the notes on PHP 5.6 creation.

append(string $string) 附加

返回一个附加了 $string 的新字符串。

  1. s('fòô')->append('bàř'); // 'fòôbàř'
at(int $index)

返回 $index 处的字符,索引从 0 开始。

  1. s('fòôbàř')->at(3); // 'b'
between(string $start, string $end [, int $offset])

返回一个 startend 之间的子字符串,或者空字符串代替。
可以提供搜索的起始偏移。

  1. s('{foo} and {bar}')->between('{', '}'); // 'foo'
camelize()

Returns a camelCase version of the string. Trims surrounding spaces,
capitalizes letters following digits, spaces, dashes and underscores,
and removes spaces, dashes, as well as underscores.

  1. s('Camel-Case')->camelize(); // 'camelCase'
chars()

Returns an array consisting of the characters in the string.

  1. s('fòôbàř')->chars(); // ['f', 'ò', 'ô', 'b', 'à', 'ř']
collapseWhitespace()

Trims the string and replaces consecutive whitespace characters with a
single space. This includes tabs and newline characters, as well as
multibyte whitespace such as the thin space and ideographic space.

  1. s(' Ο συγγραφέας ')->collapseWhitespace(); // 'Ο συγγραφέας'
contains(string $needle [, boolean $caseSensitive = true ])

Returns true if the string contains needle,falseotherwise.Bydefault,thecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('Ο συγγραφέας είπε')->contains('συγγραφέας'); // true
containsAll(array $needles [, boolean $caseSensitive = true ])

Returns true if the string contains all needles,falseotherwise.Bydefaultthecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('foo & bar')->containsAll(['foo', 'bar']); // true
containsAny(array $needles [, boolean $caseSensitive = true ])

Returns true if the string contains any needles,falseotherwise.Bydefaultthecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('str contains foo')->containsAny(['foo', 'bar']); // true
countSubstr(string $substring [, boolean $caseSensitive = true ])

Returns the number of occurrences of substringinthegivenstring.Bydefault,thecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('Ο συγγραφέας είπε')->countSubstr('α'); // 2
dasherize()

Returns a lowercase and trimmed string separated by dashes. Dashes are
inserted before uppercase characters (with the exception of the first
character of the string), and in place of spaces as well as underscores.

  1. s('fooBar')->dasherize(); // 'foo-bar'
delimit(int $delimiter)

Returns a lowercase and trimmed string separated by the given delimiter.
Delimiters are inserted before uppercase characters (with the exception
of the first character of the string), and in place of spaces, dashes,
and underscores. Alpha delimiters are not converted to lowercase.

  1. s('fooBar')->delimit('::'); // 'foo::bar'
endsWith(string $substring [, boolean $caseSensitive = true ])

Returns true if the string ends with substring,falseotherwise.Bydefault,thecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('fòôbàř')->endsWith('bàř', true); // true
ensureLeft(string $substring)

Ensures that the string begins with $substring. If it doesn't, it's prepended.

  1. s('foobar')->ensureLeft('http://'); // 'http://foobar'
ensureRight(string $substring)

Ensures that the string begins with $substring. If it doesn't, it's appended.

  1. s('foobar')->ensureRight('.com'); // 'foobar.com'
first(int $n)

Returns the first $n characters of the string.

  1. s('fòôbàř')->first(3); // 'fòô'
getEncoding()

Returns the encoding used by the Stringy object.

  1. s('fòôbàř', 'UTF-8')->getEncoding(); // 'UTF-8'
hasLowerCase()

Returns true if the string contains a lower case char, false otherwise.

  1. s('fòôbàř')->hasLowerCase(); // true
hasUpperCase()

Returns true if the string contains an upper case char, false otherwise.

  1. s('fòôbàř')->hasUpperCase(); // false
htmlDecode()

Convert all HTML entities to their applicable characters. An alias of
html_entity_decode. For a list of flags, refer to
http://php.net/manual/en/function.html-entity-decode.php

  1. s('&')->htmlDecode(); // '&'
htmlEncode()

Convert all applicable characters to HTML entities. An alias of
htmlentities. Refer to http://php.net/manual/en/function.htmlentities.php
for a list of flags.

  1. s('&')->htmlEncode(); // '&'
humanize()

Capitalizes the first word of the string, replaces underscores with
spaces, and strips '_id'.

  1. s('author_id')->humanize(); // 'Author'
indexOf(string $needle [, $offset = 0 ]);

Returns the index of the first occurrence of $needle in the string,
and false if not found. Accepts an optional offset from which to begin
the search. A negative index searches from the end

  1. s('string')->indexOf('ing'); // 3
indexOfLast(string $needle [, $offset = 0 ]);

Returns the index of the last occurrence of $needle in the string,
and false if not found. Accepts an optional offset from which to begin
the search. Offsets may be negative to count from the last character
in the string.

  1. s('foobarfoo')->indexOfLast('foo'); // 10
insert(int $index, string $substring)

Inserts substringintothestringattheindex provided.

  1. s('fòôbř')->insert('à', 4); // 'fòôbàř'
isAlpha()

Returns true if the string contains only alphabetic chars, false otherwise.

  1. s('丹尼爾')->isAlpha(); // true
isAlphanumeric()

Returns true if the string contains only alphabetic and numeric chars, false
otherwise.

  1. s('دانيال1')->isAlphanumeric(); // true
isBlank()

Returns true if the string contains only whitespace chars, false otherwise.

  1. s("\n\t \v\f")->isBlank(); // true
isHexadecimal()

Returns true if the string contains only hexadecimal chars, false otherwise.

  1. s('A102F')->isHexadecimal(); // true
isJson()

Returns true if the string is JSON, false otherwise.

  1. s('{"foo":"bar"}')->isJson(); // true
isLowerCase()

Returns true if the string contains only lower case chars, false otherwise.

  1. s('fòôbàř')->isLowerCase(); // true
isSerialized()

Returns true if the string is serialized, false otherwise.

  1. s('a:1:{s:3:"foo";s:3:"bar";}')->isSerialized(); // true
isUpperCase()

Returns true if the string contains only upper case chars, false otherwise.

  1. s('FÒÔBÀŘ')->isUpperCase(); // true
last(int $n)

Returns the last $n characters of the string.

  1. s('fòôbàř')->last(3); // 'bàř'
length()

Returns the length of the string. An alias for PHP's mb_strlen() function.

  1. s('fòôbàř')->length(); // 6
lines()

Splits on newlines and carriage returns, returning an array of Stringy
objects corresponding to the lines in the string.

  1. s("fòô\r\nbàř\n")->lines(); // ['fòô', 'bàř', '']
longestCommonPrefix(string $otherStr)

Returns the longest common prefix between the string and $otherStr.

  1. s('foobar')->longestCommonPrefix('foobaz'); // 'fooba'
longestCommonSuffix(string $otherStr)

Returns the longest common suffix between the string and $otherStr.

  1. s('fòôbàř')->longestCommonSuffix('fòrbàř'); // 'bàř'
longestCommonSubstring(string $otherStr)

Returns the longest common substring between the string and $otherStr. In the
case of ties, it returns that which occurs first.

  1. s('foobar')->longestCommonSubstring('boofar'); // 'oo'
lowerCaseFirst()

Converts the first character of the supplied string to lower case.

  1. s('Σ foo')->lowerCaseFirst(); // 'σ foo'
pad(int length[,stringpadStr = ' ' [, string $padType = 'right' ]])

Pads the string to a given length with padStr.Iflengthislessthanorequaltothelengthofthestring,nopaddingtakesplaces.Thedefaultstringusedforpaddingisaspace,andthedefaulttype(oneofleft,right,both)isright.ThrowsanInvalidArgumentExceptionifpadType isn't one of those 3 values.

  1. s('fòôbàř')->pad(9, '-/', 'left'); // '-/-fòôbàř'
padBoth(int length[,stringpadStr = ' ' ])

Returns a new string of a given length such that both sides of the string
string are padded. Alias for pad() with a $padType of 'both'.

  1. s('foo bar')->padBoth(9, ' '); // ' foo bar '
padLeft(int length[,stringpadStr = ' ' ])

Returns a new string of a given length such that the beginning of the
string is padded. Alias for pad() with a $padType of 'left'.

  1. s('foo bar')->padLeft(9, ' '); // ' foo bar'
padRight(int length[,stringpadStr = ' ' ])

Returns a new string of a given length such that the end of the string is
padded. Alias for pad() with a $padType of 'right'.

  1. s('foo bar')->padRight(10, '_*'); // 'foo bar_*_'
prepend(string $string)

Returns a new string starting with $string.

  1. s('bàř')->prepend('fòô'); // 'fòôbàř'
regexReplace(string pattern,stringreplacement [, string $options = 'msr'])

Replaces all occurrences of patterninstr by $replacement. An alias
for mb_ereg_replace(). Note that the 'i' option with multibyte patterns
in mb_ereg_replace() requires PHP 5.6+ for correct results. This is due
to a lack of support in the bundled version of Oniguruma in PHP < 5.6,
and current versions of HHVM (3.8 and below).

  1. s('fòô ')->regexReplace('f[òô]+\s', 'bàř', 'msr'); // 'bàř'
removeLeft(string $substring)

Returns a new string with the prefix $substring removed, if present.

  1. s('fòôbàř')->removeLeft('fòô'); // 'bàř'
removeRight(string $substring)

Returns a new string with the suffix $substring removed, if present.

  1. s('fòôbàř')->removeRight('bàř'); // 'fòô'
repeat(int $multiplier)

Returns a repeated string given a multiplier. An alias for str_repeat.

  1. s('α')->repeat(3); // 'ααα'
replace(string search,stringreplacement)

Replaces all occurrences of searchinstr by $replacement.

  1. s('fòô bàř fòô bàř')->replace('fòô ', ''); // 'bàř bàř'
reverse()

Returns a reversed string. A multibyte version of strrev().

  1. s('fòôbàř')->reverse(); // 'řàbôòf'
safeTruncate(int length[,stringsubstring = '' ])

Truncates the string to a given length, while ensuring that it does not
split words. If $substring is provided, and truncating occurs, the
string is further truncated so that the substring may be appended without
exceeding the desired length.

  1. s('What are your plans today?')->safeTruncate(22, '...');
  2. // 'What are your plans...'
shuffle()

A multibyte str_shuffle() function. It returns a string with its characters in
random order.

  1. s('fòôbàř')->shuffle(); // 'àôřbòf'
slugify([, string $replacement = '-' ])

Converts the string into an URL slug. This includes replacing non-ASCII
characters with their closest ASCII equivalents, removing remaining
non-ASCII and non-alphanumeric characters, and replacing whitespace with
$replacement. The replacement defaults to a single dash, and the string
is also converted to lowercase.

  1. s('Using strings like fòô bàř')->slugify(); // 'using-strings-like-foo-bar'
startsWith(string substring[,booleancaseSensitive = true ])

Returns true if the string begins with substring,falseotherwise.Bydefault,thecomparisoniscasesensitive,butcanbemadeinsensitivebysettingcaseSensitive to false.

  1. s('FÒÔbàřbaz')->startsWith('fòôbàř', false); // true
slice(int start[,intend ])

Returns the substring beginning at start,andupto,butnotincludingtheindexspecifiedbyend. If endisomitted,thefunctionextractstheremainingstring.Ifend is negative, it is computed from the end
of the string.

  1. s('fòôbàř')->slice(3, -1); // 'bà'
split(string pattern[,intlimit ])

Splits the string with the provided regular expression, returning an
array of Stringy objects. An optional integer $limit will truncate the
results.

  1. s('foo,bar,baz')->split(',', 2); // ['foo', 'bar']
substr(int start[,intlength ])

Returns the substring beginning at startwiththespecifiedlength.
It differs from the mb_substr() function in that providing a $length of
null will return the rest of the string, rather than an empty string.

  1. s('fòôbàř')->substr(2, 3); // 'ôbà'
surround(string $substring)

Surrounds a string with the given substring.

  1. s(' ͜ ')->surround('ʘ'); // 'ʘ ͜ ʘ'
swapCase()

Returns a case swapped version of the string.

  1. s('Ντανιλ')->swapCase(); // 'νΤΑΝΙΛ'
tidy()

Returns a string with smart quotes, ellipsis characters, and dashes from
Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.

  1. s('“I see…”')->tidy(); // '"I see..."'
titleize([, array $ignore])

Returns a trimmed string with the first letter of each word capitalized.
Also accepts an array, $ignore, allowing you to list words not to be
capitalized.

  1. $ignore = ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'];
  2. s('i like to watch television')->titleize($ignore);
  3. // 'I Like to Watch Television'
toAscii()

Returns an ASCII version of the string. A set of non-ASCII characters are
replaced with their closest ASCII counterparts, and the rest are removed
unless instructed otherwise.

  1. s('fòôbàř')->toAscii(); // 'foobar'
toBoolean()

Returns a boolean representation of the given logical string value.
For example, 'true', '1', 'on' and 'yes' will return true. 'false', '0',
'off', and 'no' will return false. In all instances, case is ignored.
For other numeric strings, their sign will determine the return value.
In addition, blank strings consisting of only whitespace will return
false. For all other strings, the return value is a result of a
boolean cast.

  1. s('OFF')->toBoolean(); // false
toLowerCase()

Converts all characters in the string to lowercase. An alias for PHP's
mb_strtolower().

  1. s('FÒÔBÀŘ')->toLowerCase(); // 'fòôbàř'
toSpaces([, tabLength = 4 ])

Converts each tab in the string to some number of spaces, as defined by
$tabLength. By default, each tab is converted to 4 consecutive spaces.

  1. s(' String speech = "Hi"')->toSpaces(); // ' String speech = "Hi"'
toTabs([, tabLength = 4 ])

Converts each occurrence of some consecutive number of spaces, as defined
by $tabLength, to a tab. By default, each 4 consecutive spaces are
converted to a tab.

  1. s(' fòô bàř')->toTabs();
  2. // ' fòô bàř'
toTitleCase()

Converts the first character of each word in the string to uppercase.

  1. s('fòô bàř')->toTitleCase(); // 'Fòô Bàř'
toUpperCase()

Converts all characters in the string to uppercase. An alias for PHP's
mb_strtoupper().

  1. s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'
trim([, string $chars])

Returns a string with whitespace removed from the start and end of the
string. Supports the removal of unicode whitespace. Accepts an optional
string of characters to strip instead of the defaults.

  1. s(' fòôbàř ')->trim(); // 'fòôbàř'
trimLeft([, string $chars])

Returns a string with whitespace removed from the start of the string.
Supports the removal of unicode whitespace. Accepts an optional
string of characters to strip instead of the defaults.

  1. s(' fòôbàř ')->trimLeft(); // 'fòôbàř '
trimRight([, string $chars])

Returns a string with whitespace removed from the end of the string.
Supports the removal of unicode whitespace. Accepts an optional
string of characters to strip instead of the defaults.

  1. s(' fòôbàř ')->trimRight(); // ' fòôbàř'
truncate(int length[,stringsubstring = '' ])

Truncates the string to a given length. If $substring is provided, and
truncating occurs, the string is further truncated so that the substring
may be appended without exceeding the desired length.

  1. s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'
underscored()

Returns a lowercase and trimmed string separated by underscores.
Underscores are inserted before uppercase characters (with the exception
of the first character of the string), and in place of spaces as well as dashes.

  1. s('TestUCase')->underscored(); // 'test_u_case'
upperCamelize()

Returns an UpperCamelCase version of the supplied string. It trims
surrounding spaces, capitalizes letters following digits, spaces, dashes
and underscores, and removes spaces, dashes, underscores.

  1. s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'
upperCaseFirst()

Converts the first character of the supplied string to upper case.

  1. s('σ foo')->upperCaseFirst(); // 'Σ foo'

Extensions

The following is a list of libraries that extend Stringy:

Tests

From the project directory, tests can be ran using phpunit

License

Released under the MIT License - see LICENSE.txt for details.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注